/*
buildinstall/11.0.3.3 ESD#6/P-FREE/Linux Intel/Linux 2.2.14 i686/1/OPT/Fri Mar 17 15:47:56 CET 2000

(c) Copyright 1987, 2000.
Sybase, Inc.  All rights reserved.
 
Unpublished rights reserved under U.S. copyright laws.
This software contains confidential and trade secret information of Sybase,
Inc.   Use,  duplication or disclosure of the software and documentation by
the  U.S.  Government  is  subject  to  restrictions set forth in a license
agreement  between  the  Government  and  Sybase,  Inc.  or  other  written
agreement  specifying  the  Government's rights to use the software and any
applicable FAR provisions, for example, FAR 52.227-19.

Sybase, Inc. 6475 Christie Avenue, Emeryville, CA 94608, USA.
*/
use master
go
declare @size_needed int
select @size_needed = (2560 - sum(size)) * (@@pagesize / 1024) / 1024
from sysusages where dbid = 1
if (@size_needed = 1)
begin
	alter database master on master = 1
end
else if (@size_needed = 2)
begin
	alter database master on master = 2
end
else if (@size_needed = 3)
begin
	alter database master on master = 3
end
else if (@size_needed = 4)
begin
	alter database master on master = 4
end
else if (@size_needed = 5)
begin
	alter database master on master = 5
end
else if (@size_needed = 6)
begin
	alter database master on master = 6
end
go
declare @allow_update int
select @allow_update = value from syscurconfigs
	where config = 102
if (@allow_update = 0)
begin
	select config_admin(1, 102, 1, 0, NULL, NULL)
end
go
if exists (select *
        from sysdatabases
                where name = 'sybsystemprocs')
begin
        use sybsystemprocs
end
else
        use master
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_instmsg')
begin
	print "Dropping sp_instmsg"
	drop procedure sp_instmsg
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_procxmode')
begin
	print "Dropping sp_procxmode"
	drop procedure sp_procxmode
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_validlang')
begin
	print "Dropping sp_validlang"
	drop procedure sp_validlang
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_getmessage')
begin
	print "Dropping sp_getmessage"
	drop procedure sp_getmessage
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_configure')
begin
	print "Dropping sp_configure"
	drop procedure sp_configure
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dboption')
begin
	print "Dropping sp_dboption"
	drop procedure sp_dboption
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_prtsybsysmsgs')
begin
	print "Dropping sp_prtsybsysmsgs"
	drop procedure sp_prtsybsysmsgs
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_procxmode')
begin
	print "Dropping sp_procxmode"
	drop procedure sp_procxmode
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_validlang')
begin
	print "Dropping sp_validlang"
	drop procedure sp_validlang
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_getmessage')
begin
	print "Dropping sp_getmessage"
	drop procedure sp_getmessage
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_configure')
begin
	print "Dropping sp_configure"
	drop procedure sp_configure
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dboption')
begin
	print "Dropping sp_dboption"
	drop procedure sp_dboption
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_validaltlang')
begin
	print "Dropping sp_validaltlang"
	drop procedure sp_validaltlang
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_namecrack')
begin
	print "Dropping sp_namecrack"
	drop procedure sp_namecrack
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_chklangparam')
begin
	print "Dropping sp_chklangparam"
	drop procedure sp_chklangparam
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpgroup')
begin
	print "Dropping sp_helpgroup"
	drop procedure sp_helpgroup
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpuser')
begin
	print "Dropping sp_helpuser"
	drop procedure sp_helpuser
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_locklogin')
begin
	print "Dropping sp_locklogin"
	drop procedure sp_locklogin
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_displaylogin')
begin
	print "Dropping sp_displaylogin"
	drop procedure sp_displaylogin
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addalias')
begin
	print "Dropping sp_addalias"
	drop procedure sp_addalias
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addgroup')
begin
	print "Dropping sp_addgroup"
	drop procedure sp_addgroup
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_password')
begin
	print "Dropping sp_password"
	drop procedure sp_password
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addlogin')
begin
	print "Dropping sp_addlogin"
	drop procedure sp_addlogin
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addtype')
begin
	print "Dropping sp_addtype"
	drop procedure sp_addtype
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addumpdevice')
begin
	print "Dropping sp_addumpdevice"
	drop procedure sp_addumpdevice
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addthreshold')
begin
	print "Dropping sp_addthreshold"
	drop procedure sp_addthreshold
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_modifythreshold')
begin
	print "Dropping sp_modifythreshold"
	drop procedure sp_modifythreshold
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_adduser')
begin
	print "Dropping sp_adduser"
	drop procedure sp_adduser
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addremotelogin')
begin
	print "Dropping sp_addremotelogin"
	drop procedure sp_addremotelogin
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addsegment')
begin
	print "Dropping sp_addsegment"
	drop procedure sp_addsegment
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addserver')
begin
	print "Dropping sp_addserver"
	drop procedure sp_addserver
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addlanguage')
begin
	print "Dropping sp_addlanguage"
	drop procedure sp_addlanguage
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_defaultlanguage')
begin
	print "Dropping sp_defaultlanguage"
	drop procedure sp_defaultlanguage
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helplanguage')
begin
	print "Dropping sp_helplanguage"
	drop procedure sp_helplanguage
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_droplanguage')
begin
	print "Dropping sp_droplanguage"
	drop procedure sp_droplanguage
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setlangalias')
begin
	print "Dropping sp_setlangalias"
	drop procedure sp_setlangalias
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindefault')
begin
	print "Dropping sp_bindefault"
	drop procedure sp_bindefault
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindrule')
begin
	print "Dropping sp_bindrule"
	drop procedure sp_bindrule
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_changedbowner')
begin
	print "Dropping sp_changedbowner"
	drop procedure sp_changedbowner
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_aux_getsize')
begin
	print "Dropping sp_aux_getsize"
	drop procedure sp_aux_getsize
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_expandbitmap')
begin
	print "Dropping syb_aux_expandbitmap"
	drop procedure syb_aux_expandbitmap
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privexor')
begin
	print "Dropping syb_aux_privexor"
	drop procedure syb_aux_privexor
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privnots')
begin
	print "Dropping syb_aux_privnots"
	drop procedure syb_aux_privnots
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privsand')
begin
	print "Dropping syb_aux_privsand"
	drop procedure syb_aux_privsand
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privunion')
begin
	print "Dropping syb_aux_privunion"
	drop procedure syb_aux_privunion
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_colbit')
begin
	print "Dropping syb_aux_colbit"
	drop procedure syb_aux_colbit
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_printprivs')
begin
	print "Dropping syb_aux_printprivs"
	drop procedure syb_aux_printprivs
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_aux_computeprivs')
begin
	print "Dropping sp_aux_computeprivs"
	drop procedure sp_aux_computeprivs
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_column_privileges')
begin
	print "Dropping sp_column_privileges"
	drop procedure sp_column_privileges
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_table_privileges')
begin
	print "Dropping sp_table_privileges"
	drop procedure sp_table_privileges
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_changegroup')
begin
	print "Dropping sp_changegroup"
	drop procedure sp_changegroup
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_checknames')
begin
	print "Dropping sp_checknames"
	drop procedure sp_checknames
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_commonkey')
begin
	print "Dropping sp_commonkey"
	drop procedure sp_commonkey
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_cursorinfo')
begin
	print "Dropping sp_cursorinfo"
	drop procedure sp_cursorinfo
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dboption')
begin
	print "Dropping sp_dboption"
	drop procedure sp_dboption
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_defaultdb')
begin
	print "Dropping sp_defaultdb"
	drop procedure sp_defaultdb
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_databases')
begin
	print "Dropping sp_databases"
	drop procedure sp_databases
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dbremap')
begin
	print "Dropping sp_dbremap"
	drop procedure sp_dbremap
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_remap')
begin
	print "Dropping sp_remap"
	drop procedure sp_remap
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_depends')
begin
	print "Dropping sp_depends"
	drop procedure sp_depends
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_diskdefault')
begin
	print "Dropping sp_diskdefault"
	drop procedure sp_diskdefault
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropalias')
begin
	print "Dropping sp_dropalias"
	drop procedure sp_dropalias
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropdevice')
begin
	print "Dropping sp_dropdevice"
	drop procedure sp_dropdevice
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropgroup')
begin
	print "Dropping sp_dropgroup"
	drop procedure sp_dropgroup
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropkey')
begin
	print "Dropping sp_dropkey"
	drop procedure sp_dropkey
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_droplogin')
begin
	print "Dropping sp_droplogin"
	drop procedure sp_droplogin
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropthreshold')
begin
	print "Dropping sp_dropthreshold"
	drop procedure sp_dropthreshold
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_droptype')
begin
	print "Dropping sp_droptype"
	drop procedure sp_droptype
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropuser')
begin
	print "Dropping sp_dropuser"
	drop procedure sp_dropuser
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropremotelogin')
begin
	print "Dropping sp_dropremotelogin"
	drop procedure sp_dropremotelogin
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropsegment')
begin
	print "Dropping sp_dropsegment"
	drop procedure sp_dropsegment
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropserver')
begin
	print "Dropping sp_dropserver"
	drop procedure sp_dropserver
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_estspace')
begin
	print "Dropping sp_estspace"
	drop procedure sp_estspace
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_extendsegment')
begin
	print "Dropping sp_extendsegment"
	drop procedure sp_extendsegment
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_fixindex')
begin
	print "Dropping sp_fixindex"
	drop procedure sp_fixindex
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_fkeys')
begin
	print "Dropping sp_fkeys"
	drop procedure sp_fkeys
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_foreignkey')
begin
	print "Dropping sp_foreignkey"
	drop procedure sp_foreignkey
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpconstraint')
begin
	print "Dropping sp_helpconstraint"
	drop procedure sp_helpconstraint
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpdb')
begin
	print "Dropping sp_helpdb"
	drop procedure sp_helpdb
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpdevice')
begin
	print "Dropping sp_helpdevice"
	drop procedure sp_helpdevice
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helplog')
begin
	print "Dropping sp_helplog"
	drop procedure sp_helplog
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpindex')
begin
	print "Dropping sp_helpindex"
	drop procedure sp_helpindex
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpjoins')
begin
	print "Dropping sp_helpjoins"
	drop procedure sp_helpjoins
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpkey')
begin
	print "Dropping sp_helpkey"
	drop procedure sp_helpkey
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_objectsegment')
begin
	print "Dropping sp_objectsegment"
	drop procedure sp_objectsegment
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_indsuspect')
begin
	print "Dropping sp_indsuspect"
	drop procedure sp_indsuspect
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpartition')
begin
	print "Dropping sp_helpartition"
	drop procedure sp_helpartition
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_help')
begin
	print "Dropping sp_help"
	drop procedure sp_help
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helprotect')
begin
	print "Dropping sp_helprotect"
	drop procedure sp_helprotect
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helptext')
begin
	print "Dropping sp_helptext"
	drop procedure sp_helptext
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpthreshold')
begin
	print "Dropping sp_helpthreshold"
	drop procedure sp_helpthreshold
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_lock')
begin
	print "Dropping sp_lock"
	drop procedure sp_lock
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_logdevice')
begin
	print "Dropping sp_logdevice"
	drop procedure sp_logdevice
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_lookup')
begin
	print "Dropping sp_lookup"
	drop procedure sp_lookup
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpremotelogin')
begin
	print "Dropping sp_helpremotelogin"
	drop procedure sp_helpremotelogin
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpsegment')
begin
	print "Dropping sp_helpsegment"
	drop procedure sp_helpsegment
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpsort')
begin
	print "Dropping sp_helpsort"
	drop procedure sp_helpsort
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpserver')
begin
	print "Dropping sp_helpserver"
	drop procedure sp_helpserver
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_markreport')
begin
	print "Dropping sp_markreport"
	drop procedure sp_markreport
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_monitor')
begin
	print "Dropping sp_monitor"
	drop procedure sp_monitor
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_pkeys')
begin
	print "Dropping sp_pkeys"
	drop procedure sp_pkeys
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_placeobject')
begin
	print "Dropping sp_placeobject"
	drop procedure sp_placeobject
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_primarykey')
begin
	print "Dropping sp_primarykey"
	drop procedure sp_primarykey
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_recompile')
begin
	print "Dropping sp_recompile"
	drop procedure sp_recompile
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_remoteoption')
begin
	print "Dropping sp_remoteoption"
	drop procedure sp_remoteoption
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_rename')
begin
	print "Dropping sp_rename"
	drop procedure sp_rename
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_renamedb')
begin
	print "Dropping sp_renamedb"
	drop procedure sp_renamedb
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_serveroption')
begin
	print "Dropping sp_serveroption"
	drop procedure sp_serveroption
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_serverinfo')
begin
	print "Dropping sp_serverinfo"
	drop procedure sp_serverinfo
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_server_info')
begin
	print "Dropping sp_server_info"
	drop procedure sp_server_info
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_inform')
begin
	print "Dropping sp_inform"
	drop procedure sp_inform
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setreplicate')
begin
	print "Dropping sp_setreplicate"
	drop procedure sp_setreplicate
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_spaceused')
begin
	print "Dropping sp_spaceused"
	drop procedure sp_spaceused
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sproc_columns')
begin
	print "Dropping sp_sproc_columns"
	drop procedure sp_sproc_columns
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_statistics')
begin
	print "Dropping sp_statistics"
	drop procedure sp_statistics
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sendmsg')
begin
	print "Dropping sp_sendmsg"
	drop procedure sp_sendmsg
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_stored_procedures')
begin
	print "Dropping sp_stored_procedures"
	drop procedure sp_stored_procedures
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindefault')
begin
	print "Dropping sp_unbindefault"
	drop procedure sp_unbindefault
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindrule')
begin
	print "Dropping sp_unbindrule"
	drop procedure sp_unbindrule
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_who')
begin
	print "Dropping sp_who"
	drop procedure sp_who
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_procqmode')
begin
	print "Dropping sp_procqmode"
	drop procedure sp_procqmode
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_reportstats')
begin
	print "Dropping sp_reportstats"
	drop procedure sp_reportstats
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_clearstats')
begin
	print "Dropping sp_clearstats"
	drop procedure sp_clearstats
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_datatype_info')
begin
	print "Dropping sp_datatype_info"
	drop procedure sp_datatype_info
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addmessage')
begin
	print "Dropping sp_addmessage"
	drop procedure sp_addmessage
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropmessage')
begin
	print "Dropping sp_dropmessage"
	drop procedure sp_dropmessage
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindmsg')
begin
	print "Dropping sp_bindmsg"
	drop procedure sp_bindmsg
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindmsg')
begin
	print "Dropping sp_unbindmsg"
	drop procedure sp_unbindmsg
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_role')
begin
	print "Dropping sp_role"
	drop procedure sp_role
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_modifylogin')
begin
	print "Dropping sp_modifylogin"
	drop procedure sp_modifylogin
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_auditinstall')
begin
	print "Dropping sp_auditinstall"
	drop procedure sp_auditinstall
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_volchanged')
begin
	print "Dropping sp_volchanged"
	drop procedure sp_volchanged
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_checkreswords')
begin
	print "Dropping sp_checkreswords"
	drop procedure sp_checkreswords
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_tables')
begin
	print "Dropping sp_tables"
	drop procedure sp_tables
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_special_columns')
begin
	print "Dropping sp_special_columns"
	drop procedure sp_special_columns
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_columns')
begin
	print "Dropping sp_columns"
	drop procedure sp_columns
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_aux_parse_entity')
begin
	print "Dropping sp_aux_parse_entity"
	drop procedure sp_aux_parse_entity
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_cachestrategy')
begin
	print "Dropping sp_cachestrategy"
	drop procedure sp_cachestrategy
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_chgattribute')
begin
	print "Dropping sp_chgattribute"
	drop procedure sp_chgattribute
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_cacheconfig')
begin
	print "Dropping sp_cacheconfig"
	drop procedure sp_cacheconfig
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindcache')
begin
	print "Dropping sp_bindcache"
	drop procedure sp_bindcache
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_poolconfig')
begin
	print "Dropping sp_poolconfig"
	drop procedure sp_poolconfig
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindcache')
begin
	print "Dropping sp_unbindcache"
	drop procedure sp_unbindcache
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindcache_all')
begin
	print "Dropping sp_unbindcache_all"
	drop procedure sp_unbindcache_all
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setrepcol')
begin
	print "Dropping sp_setrepcol"
	drop procedure sp_setrepcol
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setrepproc')
begin
	print "Dropping sp_setrepproc"
	drop procedure sp_setrepproc
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setreptable')
begin
	print "Dropping sp_setreptable"
	drop procedure sp_setreptable
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_logiosize')
begin
	print "Dropping sp_logiosize"
	drop procedure sp_logiosize
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpcache')
begin
	print "Dropping sp_helpcache"
	drop procedure sp_helpcache
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_displaylevel')
begin
	print "Dropping sp_displaylevel"
	drop procedure sp_displaylevel
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setpglockpromote')
begin
	print "Dropping sp_setpglockpromote"
	drop procedure sp_setpglockpromote
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropglockpromote')
begin
	print "Dropping sp_dropglockpromote"
	drop procedure sp_dropglockpromote
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_kernel')
begin
	print "Dropping sp_sysmon_kernel"
	drop procedure sp_sysmon_kernel
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_xactsum')
begin
	print "Dropping sp_sysmon_xactsum"
	drop procedure sp_sysmon_xactsum
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_xactmgmt')
begin
	print "Dropping sp_sysmon_xactmgmt"
	drop procedure sp_sysmon_xactmgmt
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_index')
begin
	print "Dropping sp_sysmon_index"
	drop procedure sp_sysmon_index
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_locks')
begin
	print "Dropping sp_sysmon_locks"
	drop procedure sp_sysmon_locks
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_dcache')
begin
	print "Dropping sp_sysmon_dcache"
	drop procedure sp_sysmon_dcache
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_pcache')
begin
	print "Dropping sp_sysmon_pcache"
	drop procedure sp_sysmon_pcache
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_memory')
begin
	print "Dropping sp_sysmon_memory"
	drop procedure sp_sysmon_memory
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_recovery')
begin
	print "Dropping sp_sysmon_recovery"
	drop procedure sp_sysmon_recovery
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_diskio')
begin
	print "Dropping sp_sysmon_diskio"
	drop procedure sp_sysmon_diskio
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_netio')
begin
	print "Dropping sp_sysmon_netio"
	drop procedure sp_sysmon_netio
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_taskmgmt')
begin
	print "Dropping sp_sysmon_taskmgmt"
	drop procedure sp_sysmon_taskmgmt
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon')
begin
	print "Dropping sp_sysmon"
	drop procedure sp_sysmon
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_shmdumpsize')
begin
	print "Dropping sp_shmdumpsize"
	drop procedure sp_shmdumpsize
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_shmdumpconfig')
begin
	print "Dropping sp_shmdumpconfig"
	drop procedure sp_shmdumpconfig
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_start_xact')
begin
	print "Dropping sp_start_xact"
	drop procedure sp_start_xact
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_commit_xact')
begin
	print "Dropping sp_commit_xact"
	drop procedure sp_commit_xact
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_abort_xact')
begin
	print "Dropping sp_abort_xact"
	drop procedure sp_abort_xact
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_remove_xact')
begin
	print "Dropping sp_remove_xact"
	drop procedure sp_remove_xact
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_stat_xact')
begin
	print "Dropping sp_stat_xact"
	drop procedure sp_stat_xact
end
go

if (select db_id()) > 1
	dump tran sybsystemprocs with truncate_only
else
	dump tran master with truncate_only
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_probe_xact')
begin
	print "Dropping sp_probe_xact"
	drop procedure sp_probe_xact
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_scan_xact')
begin
	print "Dropping sp_scan_xact"
	drop procedure sp_scan_xact
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dbupgrade')
begin
	print "Dropping sp_dbupgrade"
	drop procedure sp_dbupgrade
end
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_loaddbupgrade')
begin
	print "Dropping sp_loaddbupgrade"
	drop procedure sp_loaddbupgrade
end
go

use master
go
/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/a_permitboth */
grant select on sysalternates to public
grant select on syscolumns to public
grant select on syscomments to public
grant select on sysdepends to public
grant select on sysindexes to public
grant select on syskeys to public
grant select on sysobjects to public
revoke select on sysobjects(audflags) from public
grant select on sysobjects to sso_role
grant select on sysprocedures to public
grant select on sysprotects to public
grant select on syssegments to public
grant select on systypes to public
grant select on sysusers to public
grant select on syslogs to public
grant select on sysconstraints to public
grant select on sysreferences to public
grant select on sysusermessages to public
grant select on sysattributes to public
go
/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/a_permitmaster */
grant select on sysdatabases to public
revoke select on sysdatabases(audflags) from public
revoke select on sysdatabases(deftabaud) from public
revoke select on sysdatabases(defvwaud) from public
revoke select on sysdatabases(defpraud) from public
grant select on sysdatabases to sso_role
grant select on sysdevices to public
grant select on syslocks to public
grant select on sysmessages to public
grant select on sysprocesses to public
grant select on sysusages to public
grant select on sysconfigures to public
grant select on syscurconfigs to public
grant select on syslanguages to public
grant select on syscharsets to public


grant select on syslogins to public
revoke select on syslogins(password) to public
revoke select on syslogins(audflags) from public
grant select on syslogins to sso_role
grant select on sysservers to public
grant select on sysremotelogins to public


go
/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
set nocount on
go
use master
go
if exists (select *
	from sysobjects
		where name = "spt_values")
begin
	drop table spt_values
end
go

/* 
** Langid is filled in by langinstall
*/
create table spt_values (


name	varchar(28) NULL,

number	int,
type	char(2),
low	int NULL,
high	int NULL,
msgnum	int NULL) on system
go
create clustered index spt_valuesclust on spt_values(number, type) on system
go
set nocount on
go
insert spt_values(low, high, number, type) values (1, 1, 0, 'P')
insert spt_values(low, high, number, type) values (1, 2, 1, 'P')
insert spt_values(low, high, number, type) values (1, 4, 2, 'P')
insert spt_values(low, high, number, type) values (1, 8, 3, 'P')
insert spt_values(low, high, number, type) values (1, 16, 4, 'P')
insert spt_values(low, high, number, type) values (1, 32, 5, 'P')
insert spt_values(low, high, number, type) values (1, 64, 6, 'P')
insert spt_values(low, high, number, type) values (1, 128, 7, 'P')
go
/* 8 - 15 */
insert spt_values(low, high, number, type)
select low + 1, high, number + 8, 'P'
from spt_values
where number < 8 and number >= 0
go
/* 16 - 31 */
insert spt_values(low, high, number, type)
select low + 2, high, number + 16, 'P'
from spt_values
where number < 16 and number >= 0
go
/* 32 - 63 */
insert spt_values(low, high, number, type)
select low + 4, high, number + 32, 'P'
from spt_values
where number < 32 and number >= 0
go
/* 64 - 127 */
insert spt_values(low, high, number, type)
select low + 8, high, number + 64, 'P'
from spt_values
where number < 64 and number >= 0
go
/* 128 - 255 */
insert spt_values(low, high, number, type)
select low + 16, high, number + 128, 'P'
from spt_values
where number < 128 and number >= 0
go

/*
**  Configuration options.
** 
** Be sure to add new message values in a_messages
*/
insert spt_values(name, number, type)
  values ("CONFIGURATION OPTIONS", -1, 'C')
insert spt_values(name, number, type, low, high, msgnum)
  values ("recovery interval", 101, 'C', 1, 32767, 17015)
insert spt_values(name, number, type, low, high, msgnum)
  values ("allow updates", 102, 'C', 0, 1, 17016)
insert spt_values(name, number, type, low, high, msgnum)
  values ("user connections", 103, 'C', 5, 2147483647, 17017)
insert spt_values(name, number, type, low, high, msgnum)
  values ("memory", 104, 'C', 1000, 2147483647, 17018)
insert spt_values(name, number, type, low, high, msgnum)
  values ("open databases", 105, 'C', 5, 2147483647, 17019)
insert spt_values(name, number, type, low, high, msgnum)
  values ("locks", 106, 'C', 5000, 2147483647, 17020)
insert spt_values(name, number, type, low, high, msgnum)
  values ("open objects", 107, 'C', 100, 2147483647, 17021)
insert spt_values(name, number, type, low, high, msgnum)
  values ("procedure cache", 108, 'C', 1, 99, 17022)
go
insert spt_values(name, number, type, low, high, msgnum)
  values ("fill factor", 109, 'C', 0, 100, 17023)
insert spt_values(name, number, type, low, high, msgnum)
  values ("time slice", 110, 'C', 50, 1000, 17024)
insert spt_values(name, number, type, low, high, msgnum)
  values ("database size", 111, 'C', 2, 10000, 17025)
insert spt_values(name, number, type, low, high, msgnum)
  values ("tape retention", 112, 'C', 0, 365, 17026)
insert spt_values(name, number, type, low, high, msgnum)
  values ("recovery flags", 113, 'C', 0, 1, 17027)
insert spt_values(name, number, type, low, high, msgnum)
  values ("nested triggers", 115, 'C', 0, 1, 17029)
insert spt_values(name, number, type, low, high, msgnum)
  values ("devices", 116, 'C', 4, 256, 17030)
insert spt_values(name, number, type, low, high, msgnum)
  values ("remote access", 117, 'C', 0, 1, 17031)
insert spt_values(name, number, type, low, high, msgnum)
  values ("remote logins", 118, 'C', 0, 2147483647, 17032)
go
insert spt_values(name, number, type, low, high, msgnum)
  values ("remote sites", 119, 'C', 0, 2147483647, 17033)
insert spt_values(name, number, type, low, high, msgnum)
  values ("remote connections", 120, 'C', 0, 2147483647, 17034)
insert spt_values(name, number, type, low, high, msgnum)
  values ("pre-read packets", 121, 'C', 0, 2147483647, 17035)
insert spt_values(name, number, type, low, high, msgnum)
  values ("upgrade version", 122, 'C', 0, 2147483647, 17036)
insert spt_values(name, number, type, low, high, msgnum)
  values ("default sortorder id", 123, 'C', 0, 255, 17037)
insert spt_values(name, number, type, low, high, msgnum)
  values ("default language", 124, 'C', 0, 2147483647, 17038)
insert spt_values(name, number, type, low, high, msgnum)
  values ("language in cache", 125, 'C', 3, 100, 17039)
insert spt_values(name, number, type, low, high, msgnum)
  values ("max online engines", 126, 'C', 1, 32, 17040)
insert spt_values(name, number, type, low, high, msgnum)
  values ("min online engines", 127, 'C', 1, 32, 17041)
insert spt_values(name, number, type, low, high, msgnum)
  values ("engine adjust interval", 128, 'C', 1, 32, 17042)
go
insert spt_values(name, number, type, low, high, msgnum)
	values ("cpu flush", 129, 'C', 1, 2147483647, 17043)
insert spt_values(name, number, type, low, high, msgnum)
	values ("i/o flush", 130, 'C', 1, 2147483647, 17044)
insert spt_values(name, number, type, low, high, msgnum)
  values ("default character set id", 131, 'C', 0, 255, 17045)
/* 132 is reserved by the 4.9 group; with msgnum = 17046 */
insert spt_values(name, number, type, low, high, msgnum)
  values ("stack size", 134, 'C', 20480, 2147483647, 17046)
insert spt_values(name, number, type, low, high, msgnum)
	values ("password expiration interval", 135, 'C', 0, 32767, 17047)
insert spt_values(name, number, type, low, high, msgnum)
	values ("audit queue size", 136, 'C', 1, 65535, 17048)
insert spt_values(name, number, type, low, high, msgnum)
        values ("additional netmem", 137, 'C', 0, 2147483647, 17064)
insert spt_values(name, number, type, low, high, msgnum)
        values ("default network packet size", 138, 'C', 512, 524288, 17065)
insert spt_values(name, number, type, low, high, msgnum)
        values ("maximum network packet size", 139, 'C', 512, 524288, 17066)
insert spt_values(name, number, type, low, high, msgnum)
        values ("extent i/o buffers", 140, 'C', 0, 2147483647, 17067)
insert spt_values(name, number, type, low, high, msgnum)
        values ("identity burning set factor", 141, 'C', 1, 9999999, 17068)
insert spt_values(name, number, type, low, high, msgnum)
        values ("size of auto identity", 142, 'C', 1, 38, 17143)
insert spt_values(name, number, type, low, high, msgnum)
        values ("identity grab size", 143, 'C', 0, 2147483647, 17146)
insert spt_values(name, number, type, low, high, msgnum)
        values ("lock promotion threshold", 144, 'C', 200, 2147483647, 17147)
go

/*
** These values translate sysobjects.objaudflags, sysdatabases.deftabaud,
** sysdatabases.defviewaud, and sysdatabases.defpraud column bits into the
** actual text description of the bits.
*/
insert spt_values (name, number, type) values ("OBJECT/SPROC/TRIGGER", -1, "M")
insert spt_values (name, number, type) values ("successful deletes", 1, "M")
insert spt_values (name, number, type) values ("failed deletes", 2, "M")
insert spt_values (name, number, type) values ("successful updates", 4, "M")
insert spt_values (name, number, type) values ("failed updates", 8, "M")
insert spt_values (name, number, type) values ("successful selects", 16, "M")
insert spt_values (name, number, type) values ("failed selects", 32, "M")
insert spt_values (name, number, type) values ("successful inserts", 64, "M")
insert spt_values (name, number, type) values ("failed inserts", 128, "M")

insert spt_values (name, number, type) values
	("successful sproc/trigger", 256, "M")
insert spt_values (name, number, type) values
	("failed sproc/trigger", 512, "M")


go

/* These values translate sysdatabases.dbaudflags bits into text. */

insert spt_values (name, number, type) values ("DATABASE AUDITING", -1, "Q")
insert spt_values (name, number, type) values ("successful drop", 1, "Q")
insert spt_values (name, number, type) values ("failed drop", 2, "Q")
insert spt_values (name, number, type) values ("successful use", 4, "Q")
insert spt_values (name, number, type) values ("failed use", 8, "Q")
insert spt_values (name, number, type) values
	("successful outside access", 16, "Q")
insert spt_values (name, number, type) values ("failed outside access", 32, "Q")
insert spt_values (name, number, type) values ("successful grant", 64, "Q")
insert spt_values (name, number, type) values ("failed grant", 128, "Q")
insert spt_values (name, number, type) values ("successful revoke", 256, "Q")
insert spt_values (name, number, type) values ("failed revoke", 512, "Q")
insert spt_values (name, number, type) values ("successful truncate", 1024, "Q")
insert spt_values (name, number, type) values ("failed truncate", 2048, "Q")

go

/* These values translate syslogins.lgaudflags bits into text. */

insert spt_values (name, number, type) values ("LOGIN AUDITING", -1, "U")
insert spt_values (name, number, type) values ("successful table ref", 1, "U")
insert spt_values (name, number, type) values ("failed table ref", 2, "U")
insert spt_values (name, number, type) values ("successful view ref", 4, "U")
insert spt_values (name, number, type) values ("failed view ref", 8, "U")
insert spt_values (name, number, type) values ("command batch text", 16, "U")
go

/* Token values */
insert spt_values(name, number, type)
  values ("TOKEN VALUES", -1, 'T')
insert spt_values(name, number, type)
  values ("References", 151, 'T')
insert spt_values(name, number, type)
  values ("Update", 197, 'T')
insert spt_values(name, number, type)
  values ("Delete", 196, 'T')
insert spt_values(name, number, type)
  values ("Select", 193, 'T')
insert spt_values(name, number, type)
  values ("Insert", 195, 'T')
insert spt_values(name, number, type)
  values ("Execute", 224, 'T')
insert spt_values(name, number, type)
  values ("Grant", 205, 'T')
insert spt_values(name, number, type)
  values ("Revoke", 206, 'T')
go
insert spt_values(name, number, type)
  values ("Create Database", 203, 'T')
insert spt_values(name, number, type)
  values ("Create Default", 233, 'T')
insert spt_values(name, number, type)
  values ("Create Procedure", 222, 'T')
insert spt_values(name, number, type)
  values ("Create Rule", 236, 'T')
insert spt_values(name, number, type)
  values ("Create Table", 198, 'T')
insert spt_values(name, number, type)
  values ("Create View", 207, 'T')
insert spt_values(name, number, type)
  values ("Dump Database", 228, 'T')
insert spt_values(name, number, type)
  values ("Dump Transaction", 235, 'T')
go

/* Values for syslocks.type */
insert spt_values(name, number, type)
  values ("LOCK TYPES", -1, 'L')
insert spt_values(name, number, type)
  values ("Ex_table", 1, 'L')
insert spt_values(name, number, type)
  values ("Sh_table", 2, 'L')
insert spt_values(name, number, type)
  values ("Ex_intent", 3, 'L')
insert spt_values(name, number, type)
  values ("Sh_intent", 4, 'L')
insert spt_values(name, number, type)
  values ("Ex_page", 5, 'L')
insert spt_values(name, number, type)
  values ("Sh_page", 6, 'L')
insert spt_values(name, number, type)
  values ("Update_page", 7, 'L')
insert spt_values(name, number, type)
  values ("Ex_extent", 8, 'L')
insert spt_values(name, number, type)
  values ("Sh_extent", 9, 'L')
go
insert spt_values(name, number, type)
  values ("Ex_table-blk", 256+1, 'L')
insert spt_values(name, number, type)
  values ("Sh_table-blk", 256+2, 'L')
insert spt_values(name, number, type)
  values ("Ex_intent-blk", 256+3, 'L')
insert spt_values(name, number, type)
  values ("Sh_intent-blk", 256+4, 'L')
insert spt_values(name, number, type)
  values ("Ex_page-blk", 256+5, 'L')
insert spt_values(name, number, type)
  values ("Sh_page-blk", 256+6, 'L')
insert spt_values(name, number, type)
  values ("Update_page-blk", 256+7, 'L')
insert spt_values(name, number, type)
  values ("Ex_extent-blk", 256+8, 'L')
insert spt_values(name, number, type)
  values ("Sh_extent-blk", 256+9, 'L')
insert spt_values(name, number, type)
  values ("Ex_table-demand", 512+1, 'L')
go
insert spt_values(name, number, type)
  values ("Sh_table-demand", 512+2, 'L')
insert spt_values(name, number, type)
  values ("Ex_intent-demand", 512+3, 'L')
insert spt_values(name, number, type)
  values ("Sh_intent-demand", 512+4, 'L')
insert spt_values(name, number, type)
  values ("Ex_page-demand", 512+5, 'L')
insert spt_values(name, number, type)
  values ("Sh_page-demand", 512+6, 'L')
insert spt_values(name, number, type)
  values ("Update_page-demand", 512+7, 'L')
insert spt_values(name, number, type)
  values ("Ex_extent-demand", 512+8, 'L')
insert spt_values(name, number, type)
  values ("Sh_extent-demand", 512+9, 'L')
go
insert spt_values(name, number, type)
  values ("Ex_table-demand-blk", 512+256+1, 'L')
insert spt_values(name, number, type)
  values ("Sh_table-demand-blk", 512+256+2, 'L')
insert spt_values(name, number, type)
  values ("Ex_intent-demand-blk", 512+256+3, 'L')
insert spt_values(name, number, type)
  values ("Sh_intent-demand-blk", 512+256+4, 'L')
insert spt_values(name, number, type)
  values ("Ex_page-demand-blk", 512+256+5, 'L')
insert spt_values(name, number, type)
  values ("Sh_page-demand-blk", 512+256+6, 'L')
insert spt_values(name, number, type)
  values ("Update_page-demand-blk", 512+256+7, 'L')
insert spt_values(name, number, type)
  values ("Ex_extent-demand-blk", 512+256+8, 'L')
insert spt_values(name, number, type)
  values ("Sh_extent-demand-blk", 512+256+9, 'L')
go
insert spt_values(name, number, type)
  values ("Ex_table-request", 1024+1, 'L')
insert spt_values(name, number, type)
  values ("Sh_table-request", 1024+2, 'L')
insert spt_values(name, number, type)
  values ("Ex_intent-request", 1024+3, 'L')
insert spt_values(name, number, type)
  values ("Sh_intent-request", 1024+4, 'L')
insert spt_values(name, number, type)
  values ("Ex_page-request", 1024+5, 'L')
insert spt_values(name, number, type)
  values ("Sh_page-request", 1024+6, 'L')
insert spt_values(name, number, type)
  values ("Update_page-request", 1024+7, 'L')
insert spt_values(name, number, type)
  values ("Ex_extent-request", 1024+8, 'L')
insert spt_values(name, number, type)
  values ("Sh_extent-request", 1024+9, 'L')
go
insert spt_values(name, number, type)
  values ("Ex_table-demand-request", 1024+512+1, 'L')
insert spt_values(name, number, type)
  values ("Sh_table-demand-request", 1024+512+2, 'L')
insert spt_values(name, number, type)
  values ("Ex_intent-demand-request", 1024+512+3, 'L')
insert spt_values(name, number, type)
  values ("Sh_intent-demand-request", 1024+512+4, 'L')
insert spt_values(name, number, type)
  values ("Ex_page-demand-request", 1024+512+5, 'L')
insert spt_values(name, number, type)
  values ("Sh_page-demand-request", 1024+512+6, 'L')
insert spt_values(name, number, type)
  values ("Update_page-demand-request", 1024+512+7, 'L')
insert spt_values(name, number, type)
  values ("Ex_extent-demand-request", 1024+512+8, 'L')
insert spt_values(name, number, type)
  values ("Sh_extent-demand-request", 1024+512+9, 'L')
go

/*
**  These values define the status bits in sysindexes.
*/
insert spt_values (name, number, type)
	values ("INDEX TYPES", -1, "I")
insert spt_values (name, number, type)
	values ("nonclustered", 0, "I")
insert spt_values (name, number, type)
	values ("ignore duplicate keys", 1, "I")
insert spt_values (name, number, type)
	values ("unique", 2, "I")
insert spt_values (name, number, type)
	values ("ignore duplicate rows", 4, "I")
insert spt_values (name, number, type)
	values ("clustered", 16, "I")
insert spt_values (name, number, type)
	values ("allow duplicate rows", 64, "I")
go

/*
**  These values define the object type.  The number made from the low
**  4 bits in sysobjects.sysstats indicate the type of object.
**	
** 
** Be sure to add new message values in a_messages
*/
insert spt_values (name, number, type)
	values ("OBJECT TYPES", -1, "O")
insert spt_values (name, number, type, msgnum)
	values ("system table", 1, "O", 17101)
insert spt_values (name, number, type, msgnum)
	values ("view", 2, "O", 17102)
insert spt_values (name, number, type, msgnum)
	values ("user table", 3, "O", 17103)
insert spt_values (name, number, type, msgnum)
	values ("stored procedure",4, "O", 17104)
/* no number 5 */
insert spt_values (name, number, type, msgnum)
	values ("default", 6, "O", 17105)
insert spt_values (name, number, type, msgnum)
	values ("rule", 7, "O", 17106)
insert spt_values (name, number, type, msgnum)
	values ("trigger", 8, "O", 17100)
insert spt_values (name, number, type, msgnum)
	values ("referential constraint", 9, "O", 17140)
insert spt_values (name, number, type, msgnum)
	values ("check constraint", 10, "O", 17139)
go

/*
**  These values translate the object type's userstat bits.  If the high
**  bit is set for a sproc, then it's a report.
*/
insert spt_values (name, number, type)
	values ("REPORT TYPES", -1, "R")
insert spt_values (name, number, type)
	values ("", 0, "R")
insert spt_values (name, number, type)
	values (" (rpt)", -32768, "R")
go

/*
**  Database status bits.
**  NB -- If you add a bit here make sure you add the value to the value
**	of the ALL SETTABLE option if the user can set it.
** 
** Be sure to add new message values in a_messages
*/
insert spt_values (name, number, type)
	values ("DATABASE STATUS", -1, "D")
insert spt_values (name, number, type, msgnum)
	values ("failed upgrade", 1, "D", 17061)
insert spt_values (name, number, type, msgnum)
	values ("select into/bulkcopy", 4, "D", 17050)
insert spt_values (name, number, type, msgnum)
	values ("trunc log on chkpt", 8, "D", 17051)
insert spt_values (name, number, type, msgnum)
	values ("trunc. log on chkpt.", 8, "D", 17051)
insert spt_values (name, number, type, msgnum)
	values ("no chkpt on recovery", 16, "D", 17052)
insert spt_values (name, number, type, msgnum)
	values ("don't recover", 32, "D", 17053)
insert spt_values (name, number, type, msgnum)
	values ("not recovered", 256, "D", 17054)
insert spt_values (name, number, type, msgnum)
	values ("ddl in tran", 512, "D", 17055)
insert spt_values (name, number, type, msgnum)
	values ("read only", 1024, "D", 17056)
insert spt_values (name, number, type, msgnum)
	values ("dbo use only", 2048, "D", 17057)
go
insert spt_values (name, number, type, msgnum)
	values ("single user", 4096, "D", 17058)
insert spt_values (name, number, type, msgnum)
	values ("inconsistent security label", 16384, "D", 17060)
insert spt_values (name, number, type, msgnum)
	values ("allow nulls by default", 8192, "D", 17069)
insert spt_values (name, number, type, msgnum)
	values ("ALL SETTABLE OPTIONS", 15900, "D", 17059)
go

/*
** More database options.
** We ran out of status bits for spt_values.type = "D".  Thus,
** the type field is now char(2), and these entries describe
** the status2 options.
*/
insert spt_values (name, number, type, msgnum)
	values ("ALL SETTABLE OPTIONS", 2063, "D2", 17059)
insert spt_values (name, number, type, msgnum)
	values ("abort tran on log full", 1, "D2", 17062)
insert spt_values (name, number, type, msgnum)
	values ("no free space acctg", 2, "D2", 17063)
insert spt_values (name, number, type, msgnum)
	values ("auto identity", 4, "D2", 17145)
insert spt_values (name, number, type, msgnum)
	values ("identity in nonunique index", 8, "D2", 17144)
insert spt_values (name, number, type, msgnum)
	values ("offline", 16, "D2", 17594)
insert spt_values (name, number, type, msgnum)
	values ("disable alias access", 2048, "D2", 17438)
go

/*
**  Yes or no.
** 
** Be sure to add new message values in a_messages
*/
insert spt_values (name, number, type)
	values ("YES OR NO", -1, "B")
insert spt_values (name, number, type, msgnum)
	values ("no", 0, "B", 17010)
insert spt_values (name, number, type, msgnum)
	values ("yes", 1, "B", 17011)
go

/*
**  Status bits in sysservers
** 
** Be sure to add new message values in a_messages
*/
insert spt_values (name, number, type)
	values ("SYSSERVERS TYPES", -1, "A")
insert spt_values (name, number, type, msgnum)
	values ("timeouts", 0, "A", 17000)
insert spt_values (name, number, type, msgnum)
	values ("no timeouts", 1, "A", 17001)
insert spt_values (name, number, type, msgnum)
        values ("net password encryption", 2, "A", 17002)
go
/*
**  Status bits in sysremotelogins
** 
** Be sure to add new message values in a_messages
*/
insert spt_values (name, number, type)
	values ("SYSREMOTELOGINS TYPES", -1, "F")
insert spt_values (name, number, type, msgnum)
	values ("-- none --", 0, "F", 17661)
insert spt_values (name, number, type, msgnum)
	values ("trusted", 1, "F", 17070)
go

/*
**  Translate syskeys.type to english.
*/
insert spt_values (name, number, type)
	values ("SYSKEYS TYPES", -1, "K")
insert spt_values (name, number, type)
	values ("primary", 1, "K")
insert spt_values (name, number, type)
	values ("foreign", 2, "K")
insert spt_values (name, number, type)
	values ("common", 3, "K")
go

/*
**  Translate sysdevices.status to english.
** 
** Be sure to add new message values in a_messages
*/
insert spt_values (name, number, type)
	values ("SYSDEVICES STATUS", -1, "V")
insert spt_values (name, number, type, msgnum)
	values ("default disk", 1, "V", 17120)
insert spt_values (name, number, type, msgnum)
	values ("physical disk", 2, "V", 17121)
insert spt_values (name, number, type, msgnum)
	values ("logical disk", 4, "V", 17122)
insert spt_values (name, number, type, msgnum)
	values ("skip header", 8, "V", 17123)
insert spt_values (name, number, type, msgnum)
	values ("dump device", 16, "V", 17124)
insert spt_values (name, number, type, msgnum)
	values ("serial writes", 32, "V", 17125)
insert spt_values (name, number, type, msgnum)
	values ("device mirrored", 64, "V", 17126)
insert spt_values (name, number, type, msgnum)
	values ("reads mirrored", 128, "V", 17127)
insert spt_values (name, number, type, msgnum)
	values ("half-mirror only", 256, "V", 17128)
insert spt_values (name, number, type, msgnum)
	values ("mirror enabled", 512, "V", 17129)
go

/*
**  Translate @@options bit to english
**
**  These entries are used only by DB-Lib for
**  db{set,get}options commands
** 
** Be sure to add new message values in a_messages
*/
insert spt_values (name, number, type)
	values ("OPTIONS BITS", -1, "N")
insert spt_values (name, number, type, msgnum)
	values ("showplan", 4, "N", 17080)
insert spt_values (name, number, type, msgnum)
	values ("noexec", 5, "N", 17081)
insert spt_values (name, number, type, msgnum)
	values ("arithignore", 6, "N", 17082)
insert spt_values (name, number, type, msgnum)
	values ("arithabort", 8, "N", 17083)
insert spt_values (name, number, type, msgnum)
	values ("background", 9, "N", 17084)
insert spt_values (name, number, type, msgnum)
	values ("control", 13, "N", 17085)
insert spt_values (name, number, type, msgnum)
	values ("offsets", 14, "N", 17086)
insert spt_values (name, number, type, msgnum)
	values ("statistics io and time", 15, "N", 17087)
insert spt_values (name, number, type, msgnum)
	values ("parseonly", 16, "N", 17088)
go
insert spt_values (name, number, type, msgnum)
	values ("procid", 18, "N", 17089)
insert spt_values (name, number, type, msgnum)
	values ("rowcount", 20, "N", 17090)
insert spt_values (name, number, type, msgnum)
	values ("nocount", 23, "N", 17091)
go

/*
**  Set the DataServer machine type
**  spt_values.low is the number of bytes in a DataServer page for the
**  particular DataServer machine.
*/
insert spt_values (name, number, type, low)
	values ("DATASERVER HOST TYPE", -1, "E", 0)
go

/*
**  List the physical types that are compatible.
*/
insert spt_values (name, number, type)
	values ("COMPATIBLE TYPES", -1, "J")
insert spt_values (name, number, low, type)
	values ("binary", 1, 45, "J")
insert spt_values (name, number, low, type)
	values ("varbinary", 1, 37, "J")
insert spt_values (name, number, low, type)
	values ("bit", 2, 50, "J")
insert spt_values (name, number, low, type)
	values ("char", 3, 47, "J")
insert spt_values (name, number, low, type)
	values ("varchar", 3, 39, "J")
insert spt_values (name, number, low, type)
	values ("datetime", 4, 61, "J")
insert spt_values (name, number, low, type)
	values ("datetimn", 4, 111, "J")
insert spt_values (name, number, low, type)
	values ("smalldatetime", 4, 58, "J")
insert spt_values (name, number, low, type)
	values ("float", 5, 62, "J")
go
insert spt_values (name, number, low, type)
	values ("floatn", 5, 109, "J")
insert spt_values (name, number, low, type)
	values ("real", 5, 59, "J")
insert spt_values (name, number, low, type)
	values ("int", 6, 56, "J")
insert spt_values (name, number, low, type)
	values ("intn", 6, 38, "J")
insert spt_values (name, number, low, type)
	values ("smallint", 6, 52, "J")
insert spt_values (name, number, low, type)
	values ("tinyint", 6, 48, "J")
insert spt_values (name, number, low, type)
	values ("money", 7, 60, "J")
insert spt_values (name, number, low, type)
	values ("moneyn", 7, 110, "J")
insert spt_values (name, number, low, type)
	values ("smallmoney", 7, 122, "J")
insert spt_values (name, number, low, type)
	values ("numeric", 8, 63, "J")
go
insert spt_values (name, number, low, type)
	values ("numericn", 8, 108, "J")
insert spt_values (name, number, low, type)
	values ("decimal", 8, 55, "J")
insert spt_values (name, number, low, type)
	values ("decimaln", 8, 106, "J")
go

/*
**  Add some text for sysusages.segmap.
** 
** Be sure to add new message values in a_messages
*/
insert into spt_values (name, type, number)
	values ('SYSUSAGES SEGMAP', 'S', -1)
insert into spt_values (name, type, number, msgnum)
	values ('data only', 'S', 0, 17110)
insert into spt_values (name, type, number, msgnum)
	values ('data only', 'S', 1, 17110)
insert into spt_values (name, type, number, msgnum)
	values ('data only', 'S', 2, 17110)
insert into spt_values (name, type, number, msgnum)
	values ('data only', 'S', 3, 17110)
insert into spt_values (name, type, number, msgnum)
	values ('log only', 'S', 4, 17111)
insert into spt_values (name, type, number, msgnum)
	values ('data only', 'S', 5, 17110)
insert into spt_values (name, type, number, msgnum)
	values ('data only', 'S', 6, 17110)
insert into spt_values (name, type, number, msgnum)
	values ('data and log', 'S', 7, 17112)
go

/*
** Features supported on some platforms and not others.  low != 0 means
** supported.  Initialize to 0 here.  Each of these may be reset by platform.
*/
insert into spt_values (name, type, number, low)
	values ('PLATFORM FEATURES', 'G',-1, 0)
insert into spt_values (name, type, number, low, msgnum)
	values ('Channel Devices', 'G', 0, 0, 17075)
go

insert spt_values(name,number,type) values("Certified",1,"oc")
insert spt_values(name,number,type) values("Suspect",2,"oc")
insert spt_values(name,number,type) values("Uncertified",3,"oc")
go


/*
** Table/Index options used by stored procedure sp_chgattribute.
*/
insert into spt_values (name, number, type)
        values ('max_rows_per_page', 0, 'H')
go

/*
**  Create and initialize the table used by the sp_monitor procedure.
*/
if exists (select *
		from sysobjects
			where name = "spt_monitor")
begin
	drop table spt_monitor
end
go
create table spt_monitor
(
	lastrun 	datetime,
	cpu_busy 	int,
	io_busy 	int,
	idle 		int,
	pack_received 	int,
	pack_sent 	int,
	connections 	int,
	pack_errors	int,
	total_read 	int,
	total_write 	int,
	total_errors 	int
) on system
go

grant select on spt_monitor to public
go

insert into spt_monitor
	select
	lastrun = getdate(),
	cpu_busy = @@cpu_busy,
	io_busy = @@io_busy,
	idle = @@idle,
	pack_received = @@pack_received,
	pack_sent = @@pack_sent,
	connections = @@connections,
	pack_errors = @@packet_errors,
	total_read = @@total_read,
	total_write = @@total_write,
	total_errors = @@total_errors
go

set nocount off
go
grant select on spt_values to public
go

dump tran master with truncate_only
go
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_instmsg')
begin
	drop procedure sp_instmsg
end
go
print "Installing sp_instmsg"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/* A_MESSAGES - install system stored procedure
**		messages into sysmessages. THIS IS NOT TO BE
**		USED TO INSTALL SERVER MESSAGES.
*/

set nocount on
go


create procedure sp_instmsg
	@msg_num	int,
	@msg_text	varchar(255)
as
	declare @description varchar(255)

	select @description = description from sysmessages where
		error = @msg_num and langid is null

	if @description = @msg_text
		return 1

	if @description is not null
		delete sysmessages where error = @msg_num

	if @msg_text is null
		return 2

	insert sysmessages values
		(@msg_num, 0, 0, @msg_text, null, null)

	return 0
go

/*
**Messages for "sproc_phrases"	17000
*/

exec sp_instmsg 17000, "timeouts"
exec sp_instmsg 17001, "no timeouts"
exec sp_instmsg 17002, "net password encryption"
exec sp_instmsg 17010, "no"
exec sp_instmsg 17011, "yes"
exec sp_instmsg 17037, "default sortorder id"
exec sp_instmsg 17050, "select into/bulkcopy"
exec sp_instmsg 17051, "trunc log on chkpt"
exec sp_instmsg 17052, "no chkpt on recovery"
exec sp_instmsg 17053, "don't recover"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17054, "not recovered"
exec sp_instmsg 17055, "ddl in tran"
exec sp_instmsg 17056, "read only"
exec sp_instmsg 17057, "dbo use only"
exec sp_instmsg 17058, "single user"
exec sp_instmsg 17059, "ALL SETTABLE OPTIONS"
exec sp_instmsg 17060, "dbname has changed"
exec sp_instmsg 17061, "failed upgrade"
exec sp_instmsg 17062, "abort tran on log full"
exec sp_instmsg 17063, "no free space acctg"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17069, "allow nulls by default"
exec sp_instmsg 17070, "trusted"
exec sp_instmsg 17075, "Channel Devices"
exec sp_instmsg 17080, "showplan"
exec sp_instmsg 17081, "noexec"
exec sp_instmsg 17082, "arithignore"
exec sp_instmsg 17083, "arithabort"
exec sp_instmsg 17084, "background"
exec sp_instmsg 17085, "control"
exec sp_instmsg 17086, "offsets"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17087, "statistics io and time"
exec sp_instmsg 17088, "parseonly"
exec sp_instmsg 17089, "procid"
exec sp_instmsg 17090, "rowcount"
exec sp_instmsg 17091, "nocount"
exec sp_instmsg 17100, "trigger"
exec sp_instmsg 17101, "system table"
exec sp_instmsg 17102, "view"
exec sp_instmsg 17103, "user table"
exec sp_instmsg 17104, "stored procedure"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17105, "default"
exec sp_instmsg 17106, "rule"
exec sp_instmsg 17110, "data only"
exec sp_instmsg 17111, "log only"
exec sp_instmsg 17112, "data and log"
exec sp_instmsg 17120, "default disk"
exec sp_instmsg 17121, "physical disk"
exec sp_instmsg 17122, "logical disk"
exec sp_instmsg 17123, "skip header"
exec sp_instmsg 17124, "dump device"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17125, "serial writes"
exec sp_instmsg 17126, "device mirrored"
exec sp_instmsg 17127, "reads mirrored"
exec sp_instmsg 17128, "half-mirror only"
exec sp_instmsg 17129, "mirror enabled"
exec sp_instmsg 17130, "os_session_label"
exec sp_instmsg 17131, "maximum write"
exec sp_instmsg 17132, "current write"
exec sp_instmsg 17133, "minimum write"
exec sp_instmsg 17134, "maximum read"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17135, "current read"
exec sp_instmsg 17136, "maxhold"
exec sp_instmsg 17137, "minhold"
exec sp_instmsg 17138, "clearance"
exec sp_instmsg 17139, "check constraint"
exec sp_instmsg 17140, "referential constraint"
exec sp_instmsg 17142, "You need to be able to set curwrite label to data_high. This script will continue in spite of failure to set curwrite. Please rerun after setting your labels correctly."
exec sp_instmsg 17144, "identity in nonunique index"
exec sp_instmsg 17145, "auto identity"

/*
**Messages for "sp_getmessage"	17200
*/

exec sp_instmsg 17200, "Message number must be greater than or equal to 17000."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17201, "'%1!' is not an official language name from syslanguages."
exec sp_instmsg 17202, "Message number %1! does not exist in the %2! language."

/*
**Messages for "sp_addmessage"	17210
*/

exec sp_instmsg 17210, "Message number must be at least 20000."
exec sp_instmsg 17211, "Cannot add message until sysusermessages system table is created properly by Upgrade."
exec sp_instmsg 17212, "A message with number %1! in the specified language already exists."
exec sp_instmsg 17213, "Drop the old message first if you still wish to add this one."
exec sp_instmsg 17214, "The message has been inserted."
exec sp_instmsg 17215, "The message has not been inserted."

/*
**Messages for "sp_dropmessage"	17220
*/

exec sp_instmsg 17220, "Message number %1! does not exist."
exec sp_instmsg 17221, "Message deleted."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17222, "User '%1!' does not have permission to drop message number %2!."
exec sp_instmsg 17223, "User '%1!' does not have permission to drop message number %2! in the %3! language."

/*
**Messages for "sp_addalias"	17230
*/

exec sp_instmsg 17230, "You must be the System Administrator (SA) or the Database Owner (dbo) to execute this procedure."
exec sp_instmsg 17231, "No login with the specified name exists."
exec sp_instmsg 17232, "No user with the specified name exists in the current database."
exec sp_instmsg 17233, "'%1!' is already a user in the current database."
exec sp_instmsg 17234, "The specified user name is already aliased."
exec sp_instmsg 17235, "Alias user added."

/*
**Messages for "sp_addgroup"	17240
*/

exec sp_instmsg 17240, "'%1!' is not a valid name."
exec sp_instmsg 17241, "A user with the specified group name already exists."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17242, "A group with the specified name already exists."
exec sp_instmsg 17243, "New group added."

/*
**Messages for "sp_addlanguage"	17250
*/

exec sp_instmsg 17250, "'%1!' already exists in syslanguages."
exec sp_instmsg 17251, "'%1!' is not a valid date order."
exec sp_instmsg 17252, "'%1!' is not a valid first day."
exec sp_instmsg 17253, "'%1!' alias already exists in syslanguages."
exec sp_instmsg 17254, "Language not inserted."
exec sp_instmsg 17255, "New language inserted."

/*
**Messages for "sp_addlogin"	17260
*/

exec sp_instmsg 17260, "Can't run %1! from within a transaction."
exec sp_instmsg 17261, "Only the System Administrator (SA) may execute this procedure."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17262, "A user with the specified login name already exists."
exec sp_instmsg 17263, "Database name not valid -- login not added."
exec sp_instmsg 17264, "New login created."
exec sp_instmsg 17266, "All logins have been assigned. No more logins can be added at this time."

/*
**Messages for "sp_addremotelogin"	17270
*/

exec sp_instmsg 17270, "There is not a server named '%1!'."
exec sp_instmsg 17271, "'%1!' is the local server - remote login not applicable."
exec sp_instmsg 17272, "There is already a default-name mapping of a remote login from remote server '%1!'."
exec sp_instmsg 17273, "New remote login created."
exec sp_instmsg 17274, "'%1!' isn't a local user -- remote login denied."
exec sp_instmsg 17275, "There is already a remote user named '%1!' for remote server '%2!'."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17276, "Usage:sp_addremotelogin remoteserver [, loginame [,remotename]]"

/*
**Messages for "sp_addsegment"	17280
*/

exec sp_instmsg 17280, "No such device exists -- run sp_helpdb to list the devices for the current database."
exec sp_instmsg 17281, "The specified device is not used by the database."
exec sp_instmsg 17282, "The specified device is not a database device."
exec sp_instmsg 17283, "'%1!' is reserved exclusively as a log device."
exec sp_instmsg 17284, "'%1!' is not a valid identifier."
exec sp_instmsg 17285, "There is already a segment named '%1!'."
exec sp_instmsg 17286, "The maximum number of segments for the current database are already defined."
exec sp_instmsg 17287, "Segment created."
exec sp_instmsg 17288, "You must execute this procedure from the database in which you wish to add a segment.  Please execute 'use %1!' and try again."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17289, "Set your curwrite to the hurdle of current database."

/*
**Messages for "sp_addserver"	17290
*/

exec sp_instmsg 17290, "There is already a server named '%1!', physical name '%2!'."
exec sp_instmsg 17291, "sp_addserver servername [, local | NULL] [, physical_name]"
exec sp_instmsg 17292, "There is already a local server."
exec sp_instmsg 17293, "Server added."
exec sp_instmsg 17294, "Changing physical name of server '%1!' from '%2!' to '%3!'"
exec sp_instmsg 17295, "Adding server '%1!', physical name '%2!'"

/*
**Messages for "sp_addtype"	17300
*/

exec sp_instmsg 17300, "Usage: sp_addtype name, 'datatype' [,null | nonull | identity]"
exec sp_instmsg 17301, "'%1!' is not a valid type name."
exec sp_instmsg 17302, "A type with the specified name already exists."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17303, "Physical datatype does not exist."
exec sp_instmsg 17304, "User-defined datatypes based on the 'timestamp' datatype are not allowed."
exec sp_instmsg 17305, "Physical datatype does not allow nulls."
exec sp_instmsg 17306, "Physical type is fixed length. You cannot specify the length."
exec sp_instmsg 17307, "You must specify a length with this physical type."
exec sp_instmsg 17308, "Illegal length specified -- must be between 1 and 255."
exec sp_instmsg 17309, "Type added."

/*
**Messages for "sp_addumpdevice"	17310
*/

exec sp_instmsg 17310, "Unknown device type.  Use 'disk' or 'tape'."
exec sp_instmsg 17311, "device_name may not be NULL."
exec sp_instmsg 17312, "physicalname may not be NULL."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17314, "Device with same logical name already exists."
exec sp_instmsg 17317, "Please specify media capacity in megabytes (1 MB minimum)."
exec sp_instmsg 17318, "WARNING: specified size parameter is not used for the disk device type."
exec sp_instmsg 17319, "'Disk' device added."
exec sp_instmsg 17320, "'Tape' device added."
exec sp_instmsg 17321, "WARNING: physical device name '%1!' is not unique."

/*
**Messages for "sp_adduser"	17330
*/

exec sp_instmsg 17330, "A user with the same name already exists in the database."
exec sp_instmsg 17331, "User already has a login under a different name."
exec sp_instmsg 17332, "User already has alias access to the database."
exec sp_instmsg 17333, "No group with the specified name exists."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17334, "All user ids have been assigned."
exec sp_instmsg 17335, "New user added."

/*
**Messages for "sp_bindefault"	17340
*/

exec sp_instmsg 17340, "Default and table or usertype must be in current database."
exec sp_instmsg 17341, "Usage: sp_bindefault defaultname, objectname [, 'futureonly']"
exec sp_instmsg 17342, "No such default exists.  You must create the default first."
exec sp_instmsg 17343, "You can't bind a default to a timestamp datatype column."
exec sp_instmsg 17344, "You do not own a column of that name."
exec sp_instmsg 17345, "Default bound to column."
exec sp_instmsg 17346, "You do not own a datatype of that name."
exec sp_instmsg 17347, "Default bound to datatype."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17348, "The new default has been bound to columns(s) of the specified user datatype."
exec sp_instmsg 17349, "You cannot bind a declared default. The default must be created using create default."

/*
**Messages for "sp_bindrule"	17350
*/

exec sp_instmsg 17350, "Rule and table or usertype must be in current database."
exec sp_instmsg 17351, "Usage: sp_bindrule rulename, objectname [, 'futureonly']"
exec sp_instmsg 17352, "No such rule exists.  You must create the rule first."
exec sp_instmsg 17353, "You can't bind a rule to a text, image, or timestamp datatype column."
exec sp_instmsg 17354, "Rule bound to table column."
exec sp_instmsg 17355, "You can't bind a rule to a text, image, or timestamp datatype."
exec sp_instmsg 17356, "Rule bound to datatype."
exec sp_instmsg 17357, "The new rule has been bound to column(s) of the specified user datatype."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17358, "You cannot bind a declared constraint. The rule must be created using create rule."

/*
**Messages for "sp_changedbowner"	17360
*/

exec sp_instmsg 17360, "Only the System Administrator (SA) or the Database Owner (dbo) can change the owner of a database."
exec sp_instmsg 17361, "Can't change the owner of the master, model, tempdb or sybsystemprocs database."
exec sp_instmsg 17362, "The proposed new db owner already is a user in the database or owns the database."
exec sp_instmsg 17363, "The proposed new db owner already is aliased in the database."
exec sp_instmsg 17364, "The dependent aliases were mapped to the new dbo."
exec sp_instmsg 17365, "The dependent aliases were dropped."
exec sp_instmsg 17366, "Database owner changed."
exec sp_instmsg 17368, "Your curwrite label needs to be set correctly before you attempt to change the database owner."

/*
**Messages for "sp_changegroup"	17370
*/

exec sp_instmsg 17370, "Group changed."

/*
**Messages for "sp_chklangparam"	17373
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 17373, "List of %1! names contains spaces, which are not allowed."
exec sp_instmsg 17374, "List of %1! names has too few names."
exec sp_instmsg 17375, "List of %1! names has too many names."
exec sp_instmsg 17376, "List of %1! names has name(s) which are too long."
exec sp_instmsg 17377, "List of %1! names contains name(s) which have '%2!' non-alphabetic characters."

/*
**Messages for "sp_commitservice"	17380
*/

exec sp_instmsg 17380, "Commit service xact id doesn't exist."

/*
**Messages for "sp_commonkey"	17390
*/

exec sp_instmsg 17390, "Table or view name must be in current database."
exec sp_instmsg 17391, "First table in the common key doesn't exist."
exec sp_instmsg 17392, "Second table in the common key doesn't exist."
exec sp_instmsg 17393, "Only the table owner may define its common keys."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17394, "The tables have no such first column or the columns are of different types."
exec sp_instmsg 17395, "The tables have no such second column or the columns are of different types."
exec sp_instmsg 17396, "The tables have no such third column or the columns are of different types."
exec sp_instmsg 17397, "The tables have no such fourth column or the columns are of different types."
exec sp_instmsg 17398, "The tables have no such fifth column or the columns are of different types."
exec sp_instmsg 17399, "The tables have no such sixth column or the columns are of different types."
exec sp_instmsg 17400, "The tables have no such seventh column or the columns are of different types."
exec sp_instmsg 17401, "The tables have no such eighth column or the columns are of different types."
exec sp_instmsg 17402, "New common key added."

/*
**Messages for "sp_configure"	17410
*/

exec sp_instmsg 17410, "Configuration option doesn't exist."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17411, "Configuration option is not unique."
exec sp_instmsg 17412, "Only the System Administrator (SA) may change configuration parameters."
exec sp_instmsg 17413, "The value of the 'number of devices' must be greater than the highest VDEVNO, '%1!', defined in sysdevices."
exec sp_instmsg 17414, "You can't set the default language to a language ID that is not defined in syslanguages."
exec sp_instmsg 17415, "Configuration option value is not legal."
exec sp_instmsg 17416, "Configuration option changed. Run the RECONFIGURE command to install."
exec sp_instmsg 17417, "Maximum file descriptors or FILLM process quota too low to support requested number of user connections. Configuration variable 'user connections' will not be modified."
exec sp_instmsg 17418, "'%1!' is an invalid file command. The valid commands are 'verify', 'read', 'write', and 'restore'."
exec sp_instmsg 17419, "Configuration option changed. The SQL Server need not be rebooted since the option is dynamic."

/*
**Messages for "sp_dboption"	17420
*/

exec sp_instmsg 17420, "Settable database options."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17421, "No such database -- run sp_helpdb to list databases."
exec sp_instmsg 17422, "The 'master' database's options can not be changed."
exec sp_instmsg 17423, "Usage: sp_dboption [dbname, optname, {true | false}]"
exec sp_instmsg 17424, "Database option doesn't exist or can't be set by user."
exec sp_instmsg 17425, "Run sp_dboption with no parameters to see options."
exec sp_instmsg 17426, "Database option is not unique."
exec sp_instmsg 17427, "Only the System Administrator (SA) or the owner of the database may set db options."
exec sp_instmsg 17428, "You must be in the 'master' database in order to change database options."
exec sp_instmsg 17429, "The database is currently in use -- 'read only' option disallowed."
exec sp_instmsg 17430, "Run the CHECKPOINT command in the database that was changed."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17431, "true"
exec sp_instmsg 17432, "false"
exec sp_instmsg 17433, "Database option '%1!' turned ON for database '%2!'."
exec sp_instmsg 17434, "Database option '%1!' turned OFF for database '%2!'."
exec sp_instmsg 17435, "The 'single user' option is not valid for the 'sybsecurity' database."
exec sp_instmsg 17436, "The 'single user' option is not valid for the 'tempdb' database."
exec sp_instmsg 17438, "disable alias access"

/*
**Messages for "sp_defaultdb"	17440
*/

exec sp_instmsg 17440, "Database name not valid -- default not changed."
exec sp_instmsg 17441, "You can't change someone else's default database."
exec sp_instmsg 17442, "Default database changed."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17443, "Error in updating the default database."

/*
**Messages for "sp_defaultlanguage"	17450
*/

exec sp_instmsg 17450, "Only the System Administrator (SA) or '%1!' can change %2!'s default language."
exec sp_instmsg 17451, "This user does not exist.  Run sp_addlogin to add this user in."
exec sp_instmsg 17452, "%1!'s default language has been changed to %2!."
exec sp_instmsg 17453, "Error in changing the default language."

/*
**Messages for "sp_depends"	17460
*/

exec sp_instmsg 17460, "Object must be in the current database."
exec sp_instmsg 17461, "Object does not exist in this database."
exec sp_instmsg 17462, "Things the object references in the current database."
exec sp_instmsg 17463, "Things inside the current database that reference the object."
exec sp_instmsg 17464, "Object doesn't reference any object and no objects reference it."

/*
**Messages for "sp_diskdefault"	17470
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 17470, "No such device exists -- run sp_helpdevice to list the SQL Server devices."
exec sp_instmsg 17471, "No such device exists -- run sp_helpdevice to list the DataServer devices."
exec sp_instmsg 17472, "Usage: sp_diskdefault logicalname {defaulton | defaultoff}."

/*
**Messages for "sp_dropalias"	17480
*/

exec sp_instmsg 17480, "Alias user dropped."
exec sp_instmsg 17481, "No alias for specified user exists."

/*
**Messages for "sp_dropdevice"	17482
*/

exec sp_instmsg 17482, "Device is being used by a database. You can't drop it."
exec sp_instmsg 17483, "Device dropped."

/*
**Messages for "sp_dropdumpdevice"	17484
*/

exec sp_instmsg 17484, "No device with specified logical name exists."
exec sp_instmsg 17485, "Device is not a dump device and may not be dropped."

/*
**Messages for "sp_dropgroup"	17486
*/

exec sp_instmsg 17486, "Can't drop the group 'public'."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17487, "You cannot drop group because it owns objects in database."
exec sp_instmsg 17488, "Group has members.  It must be empty before it can be dropped."
exec sp_instmsg 17489, "Group has been dropped."

/*
**Messages for "sp_dropkey"	17490
*/

exec sp_instmsg 17490, "Usage: sp_dropkey {primary | foreign | common}, tabaname [, tabbname]"
exec sp_instmsg 17491, "Type must be 'primary', 'foreign', or 'common'."
exec sp_instmsg 17492, "The table or view named doesn't exist in the current database."
exec sp_instmsg 17493, "You must be the owner of the table or view to drop its key."
exec sp_instmsg 17494, "No primary key for the table or view exists."
exec sp_instmsg 17495, "Primary key for the table or view dropped."
exec sp_instmsg 17496, "Dependent foreign keys were also dropped."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17497, "You must supply the dependent table or view as the third parameter."
exec sp_instmsg 17498, "The dependent table or view doesn't exist in the current database."
exec sp_instmsg 17499, "No foreign key for the table or view exists."
exec sp_instmsg 17500, "Foreign key dropped."
exec sp_instmsg 17501, "No common keys exist between the two tables or views supplied."
exec sp_instmsg 17502, "Common keys dropped."

/*
**Messages for "sp_droplanguage"	17505
*/

exec sp_instmsg 17505, "Can't drop '%1!' because there are associated entries in master.dbo.sysmessages.  Run sp_droplanguage with the 'dropmessages' flag."
exec sp_instmsg 17506, "The only legal value for the second parameter is 'dropmessages'."
exec sp_instmsg 17507, "Language deleted."

/*
**Messages for "sp_droplogin"	17509
*/

exec sp_instmsg 17509, "User exists or is an alias or is a database owner in at least one database. Drop the user or the alias, or change the database ownership before dropping the login."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17511, "Login dropped."

/*
**Messages for "sp_dropremotelogin"	17512
*/

exec sp_instmsg 17512, "Remote login dropped."
exec sp_instmsg 17513, "There is no remote user '%1!' mapped to local user '%2!' from the remote server '%3!'."

/*
**Messages for "sp_dropsegment"	17520
*/

exec sp_instmsg 17520, "There is no such segment as '%1!'."
exec sp_instmsg 17521, "Can't drop the '%1!'segment completely."
exec sp_instmsg 17522, "The segment '%1!' is being used."
exec sp_instmsg 17523, "Segment '%1!' does not reference device '%2!'."
exec sp_instmsg 17524, "There is only one device mapping for the segment '%1!' -- use sp_dropsegment with no device argument."
exec sp_instmsg 17525, "Segment dropped."
exec sp_instmsg 17526, "Segment reference to device dropped."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17527, "WARNING: There are no longer any segments referencing device '%1!'.  This device will no longer be used for space allocation."
exec sp_instmsg 17528, "WARNING: There are no longer any segments referencing devices '%1!'.  These devices will no longer be used for space allocation."

/*
**Messages for "sp_dropserver"	17530
*/

exec sp_instmsg 17530, "There are still remote logins for the server '%1!'."
exec sp_instmsg 17531, "Remote logins for remote server '%1!' have been dropped."
exec sp_instmsg 17532, "Usage: sp_dropserver server [, droplogins]"
exec sp_instmsg 17533, "Server dropped."

/*
**Messages for "sp_droptype"	17540
*/

exec sp_instmsg 17540, "The type doesn't exist or you don't own it."
exec sp_instmsg 17541, "Type is being used. You cannot drop it."
exec sp_instmsg 17542, "Type has been dropped."

/*
**Messages for "sp_dropuser"	17543
*/

exec sp_instmsg 17543, "You cannot drop the 'database owner'."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17544, "You cannot drop the 'guest' user from master or tempdb."
exec sp_instmsg 17545, "You cannot drop user because user '%1!' owns objects in database."
exec sp_instmsg 17546, "You cannot drop user because user '%1!' owns types in database."
exec sp_instmsg 17547, "The dependent aliases were also dropped."
exec sp_instmsg 17548, "User has been dropped from current database."
exec sp_instmsg 17549, "You cannot drop user because user '%1!' owns grantable privileges and granted them to other users.  The user has granted the following privileges:"

/*
**Messages for "sp_extendsegment"	17550
*/

exec sp_instmsg 17550, "Segment extended."
exec sp_instmsg 17551, "Device '%1!' is now exclusively used by '%2!'"
exec sp_instmsg 17552, "This command has been ignored.  Extending the log segment on device '%1!' would leave no space for creating objects in database '%2!'."

/*
**Messages for "sp_foreignkey"	17560
*/

exec sp_instmsg 17560, "Foreign key table doesn't exist."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17561, "Primary key table doesn't exist."
exec sp_instmsg 17562, "Only the owner of the table may define a foreign key."
exec sp_instmsg 17563, "The table does not have a column named '%1!'."
exec sp_instmsg 17564, "Primary key does not exist with the same number of columns as the foreign key."
exec sp_instmsg 17565, "Primary key does not exist."
exec sp_instmsg 17566, "Datatypes of the column '%1!' in the keys are different."
exec sp_instmsg 17567, "New foreign key added."

/*
**Messages for "sp_help"	17570
*/

exec sp_instmsg 17570, "Operating System File"
exec sp_instmsg 17571, "---------------------"

/*
**Messages for "sp_helpdb"	17590
*/

exec sp_instmsg 17590, "The specified database does not exist."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17591, "no options set"
exec sp_instmsg 17592, " -- unused by any segments --"
exec sp_instmsg 17594, "offline"

/*
**Messages for "sp_helpdevice"	17610
*/

exec sp_instmsg 17610, "No such i/o device exists."
exec sp_instmsg 17611, "special"
exec sp_instmsg 17612, "disk"
exec sp_instmsg 17613, "tape"
exec sp_instmsg 17614, "UNKNOWN DEVICE"
exec sp_instmsg 17615, "MIRROR ENABLED"
exec sp_instmsg 17616, "MIRROR DISABLED"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17617, "mirror ="
exec sp_instmsg 17618, "only device '%1!' of mirror is enabled -- device '%2!' is disabled"
exec sp_instmsg 17619, "channel"
exec sp_instmsg 17620, "nonserial writes"

/*
**Messages for "sp_helpindex"	17640
*/

exec sp_instmsg 17640, "Object does not have any indexes."

/*
**Messages for "sp_helpjoins"	17650
*/

exec sp_instmsg 17650, "First table doesn't exist."
exec sp_instmsg 17651, "Second table doesn't exist."
exec sp_instmsg 17652, "Object must be in your current database."

/*
**Messages for "sp_helpkey"	17660
*/

exec sp_instmsg 17660, "No defined keys for this object."
exec sp_instmsg 17661, " -- none --"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17662, "For information on declarative integrity features : PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK CONSTRAINT, REFERENTIAL CONSTRAINT, NULL/NOT NULL, and DEFAULT, use sp_helpconstraint, a new system stored procedure."

/*
**Messages for "sp_helplanguage"	17670
*/

exec sp_instmsg 17670, "No alternate languages are available."
exec sp_instmsg 17671, "us_english is always available, even though it is not in master.dbo.syslanguages."

/*
**Messages for "sp_helplog"	17672
*/

exec sp_instmsg 17672, "In database '%1!', the log starts on device '%2!'."

/*
**Messages for "sp_helprotect"	17673
*/

exec sp_instmsg 17673, "All"
exec sp_instmsg 17674, "No such object or user exists in the database."
exec sp_instmsg 17675, "Illegal string found where the keyword grant is expected."
exec sp_instmsg 17676, "This may be a temporary object. Please execute procedure from tempdb."
exec sp_instmsg 17677, "sp_helprotect [name [, name_in_db [, 'grant']]]"

/*
**Messages for "sp_helptext"	17679
*/

exec sp_instmsg 17679, "There is no text for object '%1!'."

/*
**Messages for "sp_helpremotelogin"	17680
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 17680, "There are no remote servers defined."
exec sp_instmsg 17681, "There are no remote logins for the remote server '%1!'."
exec sp_instmsg 17682, "There are no remote logins defined."
exec sp_instmsg 17683, "There are no remote logins for '%1!'."
exec sp_instmsg 17684, "There are no remote logins."
exec sp_instmsg 17685, "There are no remote logins for '%1!' on remote server '%2!'."
exec sp_instmsg 17686, "** mapped locally **"
exec sp_instmsg 17687, "** use local name **"

/*
**Messages for "sp_helpsort"	17690
*/

exec sp_instmsg 17690, "Character Set ="
exec sp_instmsg 17691, "Sort Order ="
go

dump transaction master with truncate_only
go

exec sp_instmsg 17692, "Sort Order Description"
exec sp_instmsg 17693, "Characters, in Order"
exec sp_instmsg 17694, "Class 2 Character Set"

/*
**Messages for "sp_helpuser"	17700
*/

exec sp_instmsg 17700, "Users aliased to user."
exec sp_instmsg 17701, "The name supplied is a group name."
exec sp_instmsg 17702, "The name supplied is aliased to another user."
exec sp_instmsg 17703, "The name supplied is not a user, group, or aliased."

/*
**Messages for "sp_logdevice"	17710
*/

exec sp_instmsg 17710, "This command has been ignored.  The device specified is the only non-log device available for the database and cannot be made log-only."
exec sp_instmsg 17711, "syslogs moved."

/*
**Messages for "sp_markreport"	17712
*/

exec sp_instmsg 17712, "Report must be in your current database."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17713, "No such report exists."

/*
**Messages for "sp_objectsegment"	17714
*/

exec sp_instmsg 17714, "not applicable"

/*
**Messages for "sp_logdevice"	17715
*/

exec sp_instmsg 17715, "The last-chance threshold for database %1! is now %2! pages."
exec sp_instmsg 17716, "Could not update the last-chance threshold for database %1!"

/*
**Messages for "sp_password"	17720
*/

exec sp_instmsg 17720, "Error:  Unable to set the Password."
exec sp_instmsg 17721, "Password correctly set."

/*
**Messages for "sp_placeobject"	17730
*/

exec sp_instmsg 17730, "Use sp_logdevice to move syslogs table."
exec sp_instmsg 17731, "You can't move system tables."
exec sp_instmsg 17732, "You do not own table '%1!'."
exec sp_instmsg 17733, "There is no table named '%1!'."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17734, "There is no index named '%1!' for table '%2!'."
exec sp_instmsg 17735, "'%1!' is now on segment '%2!'."
exec sp_instmsg 17736, "You can't place a user table/index to logsegment."
exec sp_instmsg 17737, "Partitioned objects cannot be moved."

/*
**Messages for "sp_primarykey"	17740
*/

exec sp_instmsg 17740, "Only the owner of the table may define a primary key."
exec sp_instmsg 17741, "Primary key already exists on table -- drop key first."
exec sp_instmsg 17742, "The table has no such first column."
exec sp_instmsg 17743, "The table has no such second column."
exec sp_instmsg 17744, "The table has no such third column."
exec sp_instmsg 17745, "The table has no such fourth column."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17746, "The table has no such fifth column."
exec sp_instmsg 17747, "The table has no such sixth column."
exec sp_instmsg 17748, "The table has no such seventh column."
exec sp_instmsg 17749, "The table has no such eighth column."
exec sp_instmsg 17750, "New primary key added."

/*
**Messages for "sp_addtype"	17751
*/

exec sp_instmsg 17751, "Illegal precision specified -- must be between 1 and 38."
exec sp_instmsg 17752, "Illegal scale specified -- must be less than precision."

/*
**Messages for "sp_bindefault"	17753
*/

exec sp_instmsg 17753, "The column already has a default. Bind disallowed."

/*
**Messages for "sp_addtype"	17754
*/

exec sp_instmsg 17754, "Illegal precision specified -- must be between 1 and 48."
exec sp_instmsg 17755, "User types with the identity property must be numeric with a scale of 0."

/*
**Messages for "sp_recompile"	17760
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 17760, "'%1!' is a system table.  Cannot use sp_recompile on system tables."
exec sp_instmsg 17761, "Object '%1!' is not a table."
exec sp_instmsg 17762, "Each stored procedure and trigger that uses table '%1!' will be recompiled the next time it is executed."

/*
**Messages for "sp_remoteoption"	17770
*/

exec sp_instmsg 17770, "Settable remote login options."
exec sp_instmsg 17771, "There is no remote user '%1!' mapped to local user '%2!' on remote server '%3!'."
exec sp_instmsg 17772, "Usage: sp_remoteoption [remoteserver, loginame, remotename, optname, {true | false}]"
exec sp_instmsg 17773, "Remote login option doesn't exist or can't be set by user."
exec sp_instmsg 17774, "Run sp_remoteoption with no parameters to see options."
exec sp_instmsg 17775, "Remote login option is not unique."
exec sp_instmsg 17776, "Only the System Administrator (SA) may set remote login options."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17777, "Option '%1!' turned on."
exec sp_instmsg 17778, "Option '%1!' turned off."

/*
**Messages for "sp_rename"	17780
*/

exec sp_instmsg 17780, "There is already a column named '%1!' in table '%2!'."
exec sp_instmsg 17781, "Column name has been changed."
exec sp_instmsg 17782, "You do not own a table, column or index of that name in the current database."
exec sp_instmsg 17783, "There is already an index named '%1!' for table '%2!'."
exec sp_instmsg 17784, "Index name has been changed."
exec sp_instmsg 17785, "Table or view names beginning with '#' are not allowed."
exec sp_instmsg 17786, "Object name cannot be changed either because it does not exist in this database, or you don't own it, or it is a system name."
exec sp_instmsg 17787, "Newname already exists in systypes."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17788, "Newname already exists in sysobjects."
exec sp_instmsg 17789, "Object name has been changed."

/*
**Messages for "sp_renamedb"	17790
*/

exec sp_instmsg 17790, "Only the System Administrator (SA) can change the name of a database."
exec sp_instmsg 17791, "A database with the new name already exists."
exec sp_instmsg 17792, "The databases master, model, tempdb, sybsecurity and sybsystemprocs cannot be renamed."
exec sp_instmsg 17793, "System Administrator (SA) must set database '%1!' to single-user mode with sp_dboption before using sp_renamedb."
exec sp_instmsg 17794, "Database is renamed and in single-user mode."
exec sp_instmsg 17795, "System Administrator (SA) must reset it to multi-user mode with sp_dboption."

/*
**Messages for "sp_serverinfo"	17796
*/

exec sp_instmsg 17796, "Legal request codes are as follows:"

/*
**Messages for "sp_serveroption"	17800
*/

exec sp_instmsg 17800, "No such server -- run sp_helpserver to list servers."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17801, "Usage: sp_serveroption [server, optname, {true | false}]"
exec sp_instmsg 17802, "Server option doesn't exist or can't be set by user."
exec sp_instmsg 17803, "Run sp_serveroption with no parameters to see options."
exec sp_instmsg 17804, "Server option is not unique."
exec sp_instmsg 17805, "Only the System Administrator (SA) may set server options."
exec sp_instmsg 17806, "Option can be set for remote servers only -- not the local server."
exec sp_instmsg 17807, "Settable server options."

/*
**Messages for "sp_setlangalias"	17810
*/

exec sp_instmsg 17810, "Language alias not changed."
exec sp_instmsg 17811, "Language alias reset."

/*
**Messages for "sp_spaceused"	17830
*/

exec sp_instmsg 17830, "Object is stored in 'sysprocedures' and has no space allocated directly."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17831, "Views don't have space allocated."
exec sp_instmsg 17832, "Not avail."

/*
**Messages for "sp_unbindefault"	17840
*/

exec sp_instmsg 17840, "Column or usertype must be in current database."
exec sp_instmsg 17841, "Default unbound from table column."
exec sp_instmsg 17842, "The specified column has no default."
exec sp_instmsg 17843, "You do not own a table with a column of that name."
exec sp_instmsg 17844, "You do not own a user datatype of that name."
exec sp_instmsg 17845, "The specified user datatype has no default."
exec sp_instmsg 17846, "Default unbound from datatype."
exec sp_instmsg 17847, "Columns of the user datatype specified had their defaults unbound."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17848, "You cannot unbind a declared default. Use ALTER TABLE command."

/*
**Messages for "sp_unbindrule"	17850
*/

exec sp_instmsg 17850, "Rule unbound from table column."
exec sp_instmsg 17851, "The specified column has no rule."
exec sp_instmsg 17852, "The specified user datatype has no rule."
exec sp_instmsg 17853, "Rule unbound from datatype."
exec sp_instmsg 17854, "Columns of the user datatype specified had their rules unbound."
exec sp_instmsg 17855, "You cannot unbind a declared constraint. Use ALTER TABLE command."

/*
**Messages for "sp_indsuspect"	17860
*/

exec sp_instmsg 17860, "Suspect indexes in database %1!:"
exec sp_instmsg 17861, "There are no suspect indexes in database %1!."
exec sp_instmsg 17862, "Table must be in the current database."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17863, "There is no table named %1! in the current database."
exec sp_instmsg 17864, "Suspect indexes on table %1!:"
exec sp_instmsg 17865, "There are no suspect indexes on table %1!."

/*
**Messages for "sp_addthreshold"	17870
*/

exec sp_instmsg 17870, "Table '%1!' does not exist in database '%2!' -- cannot add thresholds."
exec sp_instmsg 17871, "There is no segment named '%1!'."
exec sp_instmsg 17872, "This threshold is too close to one or more existing thresholds.  Thresholds must be no closer than 128 pages to each other."
exec sp_instmsg 17873, "Adding threshold for segment '%1!' at '%2!' pages."
exec sp_instmsg 17874, "A threshold at %1! pages is logically impossible for segment '%2!'.  Choose a value between %3! and %4! pages."
exec sp_instmsg 17875, "Only the DBO of database '%1!' or a user with System Administrator (SA) role may add, delete, or modify thresholds in that database."
exec sp_instmsg 17876, "Warning: The specified threshold level is greater than the existing number of free pages on this segment."

/*
**Messages for "sp_auth"	17880
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 17880, "No such account -- nothing changed."
exec sp_instmsg 17881, "Invalid role -- nothing changed."
exec sp_instmsg 17882, "Invalid role -- nothing changed. The user must already have System Administrator (SA) role before being granted the Sybase Technical Support role."
exec sp_instmsg 17883, "Cannot revoke System Security Officer (SSO) role from the last remaining unlocked System Security Officer (SSO) account."
exec sp_instmsg 17884, "Neither 'grant' or 'revoke' is specified -- nothing changed."
exec sp_instmsg 17885, "Authorization updated."
exec sp_instmsg 17886, "Error in updating role."
exec sp_instmsg 17887, "Cannot revoke System Administrator (SA) role from the last remaining unlocked System Administrator (SA) account."
exec sp_instmsg 17888, "You must possess either the System Administrator (SA) or System Security Officer (SSO) role to execute %1!."

/*
**Messages for "sp_bindmsg"	17890
*/

exec sp_instmsg 17890, "Constraint name must be in `current' database."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17891, "Constraint name must belong to the current user."
exec sp_instmsg 17892, "Message id must be a user defined message."
exec sp_instmsg 17893, "No such message exists. Please create the message first using sp_addmessage."
exec sp_instmsg 17894, "No such referential or check constraint exists. Please check whether the constraint name is correct."
exec sp_instmsg 17895, "Constraint is bound to a message. You must unbind the message first."
exec sp_instmsg 17896, "Binding message failed unexpectedly. Please try again."
exec sp_instmsg 17897, "Message bound to constraint."

/*
**Messages for "sp_clearstats"	17900
*/

exec sp_instmsg 17900, "%1! login account(s) cleared."

/*
**Messages for "sp_dropthreshold"	17903
*/

exec sp_instmsg 17903, "Table '%1!' does not exist in database '%2!' -- cannot drop thresholds."
exec sp_instmsg 17904, "Segment '%1!' does not have a threshold at '%2!' pages."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17905, "You may not drop the log's last-chance threshold."
exec sp_instmsg 17906, "Dropping threshold for segment '%1!' at '%2!' pages."

/*
**Messages for "sp_helpthreshold"	17910
*/

exec sp_instmsg 17910, "Database '%1!' has no thresholds -- table '%2!' does not exist."
exec sp_instmsg 17911, "Segment '%1!' does not exist."

/*
**Messages for "sp_lockaccount"	17912
*/

exec sp_instmsg 17912, "Error in locking the account."
exec sp_instmsg 17913, "Locked account(s):"
exec sp_instmsg 17914, "Account unlocked."
exec sp_instmsg 17915, "Warning: the specified account is currently active."
exec sp_instmsg 17916, "Cannot lock the last remaining unlocked SSO login."
exec sp_instmsg 17917, "Error: locktype must either be 'lock' or 'unlock'."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17918, "Nothing changed."
exec sp_instmsg 17919, "Account locked."

/*
**Messages for "sp_modifylogin"	17920
*/

exec sp_instmsg 17920, "The given security label value is syntactically wrong."
exec sp_instmsg 17921, "The given maxwrite value cannot dominate the minwrite value from syslogins -- nothing changed."
exec sp_instmsg 17922, "The given minwrite value is not dominated by the maxwrite value from syslogins -- nothing changed."
exec sp_instmsg 17923, "The given security label is not dominated by the clearance value from syslogins -- nothing changed."
exec sp_instmsg 17924, "The given clearance value cannot dominate the %1! value from syslogins -- nothing changed."
exec sp_instmsg 17925, "Column name invalid -- nothing changed."
exec sp_instmsg 17926, "Column changed."
exec sp_instmsg 17927, "Error in changing the value of the specified column."

/*
**Messages for "sp_setsproc"	17935
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 17935, "Error in updating checkauths in memory -- nothing changed."
exec sp_instmsg 17936, "Neither 'on' or 'off' is specified -- nothing changed."
exec sp_instmsg 17937, "Error in updating checkauths in Sysobjects."

/*
**Messages for "sp_unbindmsg"	17940
*/

exec sp_instmsg 17940, "Constraint is not bound to any message."
exec sp_instmsg 17941, "Unbinding message failed unexpectedly. Please try again."
exec sp_instmsg 17942, "Message unbound from constraint."

/*
**Messages for "sp_displayaccount"	17943
*/

exec sp_instmsg 17943, "Suid: %1!"
exec sp_instmsg 17944, "Loginame: %1!"
exec sp_instmsg 17945, "Fullname: %1!"
exec sp_instmsg 17946, "Maximum Write Level: %1!"
go

dump transaction master with truncate_only
go

exec sp_instmsg 17947, "Minimum Write Level: %1!"
exec sp_instmsg 17948, "Maximum Read Level: %1!"
exec sp_instmsg 17949, "Locked: %1!"
exec sp_instmsg 17950, "Date of Last Password Change: %1!"
exec sp_instmsg 17951, "Configured Authorization:"

/*
**Messages for "sp_setreplicate"	17960
*/

exec sp_instmsg 17960, "Replication Server support is not enabled.  Replication Server support must be enabled before you can change the replication status of '%1!'."
exec sp_instmsg 17961, "Usage: sp_setreplicate object_name, {true | false}"
exec sp_instmsg 17962, "The replication status for '%1!' is already set to %2!. Replication status for '%3!' does not change."
exec sp_instmsg 17963, "An object with the same name, but owned by a different user is already being replicated.  The object '%1!' cannot be replicated."
exec sp_instmsg 17964, "The replication status for '%1!' is set to %2!."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17965, "The replication status for '%1!' is currently %2!."
exec sp_instmsg 17966, "Due to system failure, the replication status for '%1!' has not been changed."
exec sp_instmsg 17967, "Only the System Administrator (SA) or the Database Owner (DBO) may execute this stored procedure."

/*
**Messages for "sp_syntax"	17970
*/

exec sp_instmsg 17970, "sp_syntax provides syntax help for Sybase products."
exec sp_instmsg 17971, "These modules are installed on this Server:"
exec sp_instmsg 17972, "Usage: sp_syntax command [, module [, language]]"
exec sp_instmsg 17973, "No command or routine has a name like '%%%1!%%'"
exec sp_instmsg 17974, "No module has a name like '%%%1!%%'"
exec sp_instmsg 17975, "No command or routine has a name like '%%%1!%%' and a module like '%%%2!%%'"

/*
**Messages for "sp_auditdatabase"	17976
*/

exec sp_instmsg 17976, "No databases currently have auditing enabled."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17977, "'%1!' does not exist."
exec sp_instmsg 17978, "'%1!' has the following auditing options enabled:"
exec sp_instmsg 17979, "Invalid second argument.  Valid choices are 'ok', 'fail', 'both', or 'off'."
exec sp_instmsg 17980, "Invalid third argument.  Valid choices are 'd', 'u', 'o', 'g', 'r', or 't'."
exec sp_instmsg 17981, "Error updating the audit flags in the system catalogs. This is a system error.  Contact a user with System Administrator (SA) role."
exec sp_instmsg 17982, "Audit option has been changed and has taken effect immediately."
exec sp_instmsg 17983, "Audit option has been changed and will take effect after a reboot."
exec sp_instmsg 17984, "Error updating the audit flags in memory.  This is a system error.  Contact a user with System Administrator (SA) role."

/*
**Messages for "sp_auditinstall"	17985
*/

exec sp_instmsg 17985, "You must be in the sybsecurity database to run this procedure."
exec sp_instmsg 17986, "Device name ignored because no segment name was provided."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17987, "Segment '%1!' does not exist in the sybsecurity database."
exec sp_instmsg 17988, "Creating segment '%1!' on device '%2!'..."
exec sp_instmsg 17989, "Creating sysaudits table on the '%1!' segment..."
exec sp_instmsg 17990, "Dumping transaction log in sybsecurity with no_log..."

/*
**Messages for "sp_auditlogin"	17991
*/

exec sp_instmsg 17991, "No logins currently have auditing enabled."
exec sp_instmsg 17992, "Invalid second argument.  Valid options are 'table', 'view', or 'cmdtext'."
exec sp_instmsg 17993, "'%1!' is not a valid argument."

/*
**Messages for "sp_auditobject"	17994
*/

exec sp_instmsg 17994, "Only 'default table' or 'default view' is allowed."
exec sp_instmsg 17995, "Only 'ok', 'fail', 'both' or 'off' can be specified."
exec sp_instmsg 17996, "You must provide 'ok', 'fail', 'both', or 'off' preceding the 'dusi' string."
go

dump transaction master with truncate_only
go

exec sp_instmsg 17997, "Error:  An invalid letter was specified.  Use only 'd', 'u', 's', or 'i'."
exec sp_instmsg 17998, "No databases currently have %1! auditing enabled."
exec sp_instmsg 17999, "'%1!' has the following %2! auditing options enabled."
exec sp_instmsg 18000, "No objects currently have auditing enabled."
exec sp_instmsg 18001, "An object name must be provided."

/*
**Messages for "sp_auditoption"	18002
*/

exec sp_instmsg 18002, "You must provide an audit option."
exec sp_instmsg 18003, "Audit option '%1!' does not exist.  Valid options are:"
exec sp_instmsg 18004, "Audit option '%1!' is ambiguous.  Ambiguous options are:"
exec sp_instmsg 18005, "'%1!' is an invalid audit option string in this context."

/*
**Messages for "sp_auditsproc"	18006
*/

exec sp_instmsg 18006, "The third argument was not necessary; therefore, it was ignored."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18007, "No databases currently have default sproc/trigger auditing enabled."
exec sp_instmsg 18008, "'%1!' has the following default sproc/trigger auditing enabled:"
exec sp_instmsg 18009, "No sprocs/triggers currently have auditing enabled."
exec sp_instmsg 18010, "A sproc/trigger name or 'all' must be provided."

/*
**Messages for "sp_auditobject"	18011
*/

exec sp_instmsg 18011, "Object name must be qualified with the owner name."

/*
**Messages for "sp_auditsproc"	18012
*/

exec sp_instmsg 18012, "Sproc/trigger name must be qualified with the owner name."

/*
**Messages for "sp_lockaccount"	18013
*/

exec sp_instmsg 18013, "Cannot lock the last remaining unlocked SA account."

/*
**Messages for "sp_configurelogin"	18015
*/

exec sp_instmsg 18015, "%1! must be a valid sensitivity_boundary label."
exec sp_instmsg 18016, "The connection label supplied is an invalid sensitivity label."
exec sp_instmsg 18017, "%1! must dominate %2!."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18018, "New login configured."

/*
**Messages for "sp_trustlogin"	18019
*/

exec sp_instmsg 18019, "Must specify 'on' or 'off'."
exec sp_instmsg 18020, "Account updated."

/*
**Messages for "sp_auditobject"	18021
*/

exec sp_instmsg 18021, "Object name may be qualified with the owner name only; please don't qualify with the database name."

/*
**Messages for "sp_auditsproc"	18022
*/

exec sp_instmsg 18022, "Procedure/trigger name may be qualified with the owner name only; please don't qualify with the database name."

/*
**Messages for "sp_trustlogin"	18023
*/

exec sp_instmsg 18023, "The optional %1! and %2!  labels must all be non-NULL if at least one of them is specified."

/*
**Messages for "sp_helpconstr"	18024
*/

exec sp_instmsg 18024, "Object does not have any declarative constraints."

/*
**Messages for "sp_sproclabels"	18025
*/

exec sp_instmsg 18025, "Non-NULL labels specified in 'off' action."
exec sp_instmsg 18026, "Illegal action command specified."
exec sp_instmsg 18027, "Procedure remains in a non-executable state."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18028, "Certified state modified for object '%1!'."
exec sp_instmsg 18029, "The procedures label configuration has changed."
exec sp_instmsg 18030, "No change, update failed with error: %1!"

/*
**Messages for "sp_modifythreshold"	18031
*/

exec sp_instmsg 18031, "This procedure can only affect thresholds in the current database.  Say 'USE %1!', then run this procedure again."
exec sp_instmsg 18032, "You may not alter the free space or segment name of the log's last-chance threshold."

/*
**Messages for "sp_dropuser"	18033
*/

exec sp_instmsg 18033, "You cannot drop user because user '%1!' owns thresholds in database."

/*
**Messages for "sp_auditinstall"	18034
*/

exec sp_instmsg 18034, "The sysaudits table already exists.  This table will be truncated and re-used.  Therefore, segment and device parameters, if supplied, will be ignored."

/*
**Messages for "sp_checkreswords"	18035
*/

exec sp_instmsg 18035, "Reserved Words Used as Database Object Names for Database,"
exec sp_instmsg 18036, " Upgrade renames sysobjects.schema to sysobjects.schemacnt."
exec sp_instmsg 18037, " Found no reserved words used as names for database-wide objects."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18038, " Found no reserved words used as database object names."

/*
**Messages for "sp_pkeys"	18039
*/

exec sp_instmsg 18039, "Table qualifier must be name of current database."
exec sp_instmsg 18040, "Catalog procedure '%1!' can not be run in a transaction."

/*
**Messages for "sp_stored_procedures"	18041
*/

exec sp_instmsg 18041, "Stored procedure qualifier must be name of current database."

/*
**Messages for "sp_special_columns"	18042
*/

exec sp_instmsg 18042, "Illegal value for 'col_type' argument. Legal values are 'V' or 'R'."

/*
**Messages for "sp_fkeys"	18043
*/

exec sp_instmsg 18043, "primary key table name or foreign key table name must be given."
exec sp_instmsg 18044, "%1! table qualifier must be name of current database."

/*
**Messages for "sp_locklogin"	18045
*/

exec sp_instmsg 18045, "Cannot lock the last remaining unlocked SA login."

/*
**Messages for "sp_role"	18046
*/

exec sp_instmsg 18046, "Cannot revoke the SA role from the last remaining unlocked SA login."

/*
**Messages for "sp_syntax"	18047
*/

exec sp_instmsg 18047, "There is not enough room in the default devices to create the sybsyntax database."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18048, "The sybsyntax database could not be created."
exec sp_instmsg 18049, " Syntax Help"

/*
**Messages for "sp_fkeys"	18050
*/

exec sp_instmsg 18050, "Foreign key"
exec sp_instmsg 18051, "Primary key"

/*
**Messages for "sp_lock"	18052
*/

exec sp_instmsg 18052, "The class column will display the cursor name for locks associated with a cursor for the current user and the cursor id for other users."

/*
**Messages for "sp_dropuser"	18053
*/

exec sp_instmsg 18053, "User '%1!' was granted grantable privileges by the following users:"

/*
**Messages for "sp_estspace"	18054
*/

exec sp_instmsg 18054, "Table contains text/image type columns. You must specify the total length per row for these columns in the argument list."

/*
**Messages for "sp_fixindex"	18055
*/

exec sp_instmsg 18055, "Procedure should be used on system tables only."
exec sp_instmsg 18056, "Cannot re-create index on this table."
exec sp_instmsg 18057, "The index with id 1 on sysobjects can not be recreated."

/*
**Messages for "sp_rename"	18058
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 18058, "Name of user-defined type name changed."

/*
**Messages for "sp_server_info"	18059
*/

exec sp_instmsg 18059, "Attribute id %1! is not supported."

/*
**Messages for "sp_crtsybsystemprocs"	18060
*/

exec sp_instmsg 18060, "The database sybsystemprocs needs to be atleast %1!MB in size. It is currently at %2!MB."
exec sp_instmsg 18061, "Installing system stored procedures in the sybsystemprocs database."
exec sp_instmsg 18062, "Database sybsystemprocs of size %1!MB is being created on the default device."
exec sp_instmsg 18063, "Done creating database sybsystemprocs on the default device."
exec sp_instmsg 18064, "Cannot create database sybsystemprocs of size %1!MB on the default device because there is not enough space. Please create this database elsewhere and rerun the installmaster script."

/*
**Messages for "sp_auditsproc"	18065
*/

exec sp_instmsg 18065, "Illegal fourth argument. Valid arguments are: 'access', 'trusted_invocation'"

/*
**Messages for "sp_auditdatabase"	18066
*/

exec sp_instmsg 18066, "Invalid third argument.  Valid choices are 'd', 'u', 'o', 'g', 'r', 't' or 'a'"

/*
**Messages for "sp_displaylogin"	18067
*/

exec sp_instmsg 18067, "Clearance Level: %1!"

/*
**Messages for "sproclabels"	18068
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 18068, "Stored Procedure/ Trigger does not exist in this database"

/*
**Messages for "sp_grantlogin"	18069
*/

exec sp_instmsg 18069, "Access granted."

/*
**Messages for "sp_revokelogin"	18070
*/

exec sp_instmsg 18070, "Access revoked."

/*
**Messages for "sp_rename"	18071
*/

exec sp_instmsg 18071, "Set curwrite to the level of table/column."

/*
**Messages for "sp_addsegment"	18072
*/

exec sp_instmsg 18072, "Setting curwrite to data_low for updating syssegments failed."

/*
**Messages for "sp_auditdatabase"	18073
*/

exec sp_instmsg 18073, "Set command failed. Set your maxwrite and minwrite labels to correct level."

/*
**Messages for "sp_auditobject"	18074
*/

exec sp_instmsg 18074, "Curwrite label could not be set to the object level. Set your maxwrite and minwrite labels correctly."

/*
**Messages for "sp_dropgroup"	18075
*/

exec sp_instmsg 18075, "Set your maxwrite label correctly."

/*
**Messages for "sp_droptype"	18076
*/

exec sp_instmsg 18076, "Could not set curwrite to object level. Set your maxwrite label correctly."

/*
**Messages for "sp_rename"	18077
*/

exec sp_instmsg 18077, "Set curwrite to the level of index."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18078, "Set curwrite to the level of the object in systypes."
exec sp_instmsg 18079, "Set curwrite to the level of the object in sysobjects."
exec sp_instmsg 18080, "Certified state of object '%1!' has been set to 'Suspect'."

/*
**Messages for "sp_sproclabels"	18081
*/

exec sp_instmsg 18081, "Object name cannot be NULL if action is non-NULL."
exec sp_instmsg 18082, "At least one of the labels must be non-NULL."

/*
**Messages for "sp_configurelogin"	18083
*/

exec sp_instmsg 18083, "Login account %1! has already been configured. Use sp_trustlogin to modify security profile of this account."

/*
**Messages for "sp_addthreshold, sp_modifythreshold"	18084
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 18084, "A threshold at %1! pages for segment '%2!' is too close to the maximum size of the database. Because of this, the threshold will not fire more than once per SQL server re-boot. Modify the value using sp_modifythreshold to be between %3! and %4! pages."

/*
**Messages for "sp_helpartition"	18085
*/

exec sp_instmsg 18085, "Object is not partitioned."

/*
**Messages for "sp_bindcache"	18086
*/

exec sp_instmsg 18086, "Specified named cache does not exist."
exec sp_instmsg 18087, "You must be in Master to bind or unbind a database."
exec sp_instmsg 18088, "The target database does not exist."
exec sp_instmsg 18089, "The 'master' database cannot be bound to or unbound from a named cache."
exec sp_instmsg 18090, "The target object does not exist."
exec sp_instmsg 18091, "The target index does not exist."
exec sp_instmsg 18092, "Only logs may be bound to this cache."

/*
**Messages for "sp_movemass"	18093
*/

exec sp_instmsg 18093, "The specified source buffer pool does not exist."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18094, "Not enough memory in source buffer pool to satisfy request."
exec sp_instmsg 18095, "The destination buffer pool size must be a minimum of 512 kilobytes."
exec sp_instmsg 18096, "Request will result in creating a source buffer pool less than the minimum of 512 kilobytes."

/*
**Messages for "sp_procqmode"	18097
*/

exec sp_instmsg 18097, "Object must be a trigger, view or stored procedure."

/*
**Messages for "sp_bindcache"	18098
*/

exec sp_instmsg 18098, "Individual tables in 'tempdb' cannot be bound to or unbound from named caches. However, all of 'tempdb' may be bound or unbound."

/*
**Messages for "sp_setrepdb"	18099
*/

exec sp_instmsg 18099, "Usage: sp_setrepdb {true | false}"

/*
**Messages for "sp_setreptable"	18100
*/

exec sp_instmsg 18100, "Usage: sp_setreptable table_name, {true | false}"
exec sp_instmsg 18101, "The specified table must be in the current database."
exec sp_instmsg 18102, "Table '%1!' does not exist in this database."
exec sp_instmsg 18103, "An object with the same name, but owned by a different user, is already being replicated.  The table '%1!' cannot be replicated."

/*
**Messages for "sp_setrepproc"	18104
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 18104, "table"
exec sp_instmsg 18105, "function"
exec sp_instmsg 18106, "The specified stored procedure must be in the current database."
exec sp_instmsg 18107, "Stored procedure '%1!' does not exist in this database."
exec sp_instmsg 18108, "Usage: sp_setrepproc procedure_name, {function | table | false}"

/*
**Messages for "sp_setrepcol"	18109
*/

exec sp_instmsg 18109, "Usage: sp_setrepcol table_name, column_name, {do_not_replicate | always_replicate | replicate_if_changed}"
exec sp_instmsg 18110, "The table '%1!' is not marked as replicated."
exec sp_instmsg 18111, "do_not_replicate"
exec sp_instmsg 18112, "always_replicate"
exec sp_instmsg 18113, "replicate_if_changed"
go

dump transaction master with truncate_only
go

exec sp_instmsg 18114, "A table name must be provided."
exec sp_instmsg 18115, "No Text/Image columns in '%1!'."
exec sp_instmsg 18116, "The replication status for all Text/Image columns in '%1!' is set to %2!."
exec sp_instmsg 18117, "Column '%1!' does not exist in '%2!' or it is not a Text/Image column."
exec sp_instmsg 18118, "Object '%1!' does not exist in this database."

/*
**Messages for "sp_procqmode"	18119
*/

exec sp_instmsg 18119, "pre-System 11"
exec sp_instmsg 18120, "System 11 or later"

/*
**Messages for "sp_chgattribute"	18121
*/

exec sp_instmsg 18121, "Unrecognized change attribute option."
exec sp_instmsg 18122, "'%1!' attribute of object '%2!' changed to %3!."

/*
**Messages for "sp_configure"	18123
*/

exec sp_instmsg 18123, "Configuration option changed. The SQL Server must be rebooted before the change in effect since the option is static."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18124, "No matching configuration options.  Here is a listing of groups:"
exec sp_instmsg 18125, "Must provide the parameter 'filename'."

/*
**Messages for "sp_logiosize"	18126
*/

exec sp_instmsg 18126, "Log I/O Size must be a power of 2. For example: 2, 4, 8 and 16."
exec sp_instmsg 18127, "You must have System Administrator (SA) role to execute this stored procedure."
exec sp_instmsg 18128, "Unable to change the log I/O size. The memory pool for the specified log I/O size does not exist."
exec sp_instmsg 18129, "Log I/O size is set to %1! Kbytes."
exec sp_instmsg 18130, "sp_logiosize failed. Please contact Sybase Technical Support to help you resolve the problem."
exec sp_instmsg 18131, "Log I/O Size value '%1!' is illegal."
exec sp_instmsg 18132, "The transaction log for database '%1!' will use I/O size of %2! Kbytes."

/*
**Messages for "sp_configure"	18133
*/

exec sp_instmsg 18133, "The character set, '%1!', is invalid since it is not defined in Syscharsets."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18134, "The sortorder, '%1!', is invalid since it is not defined in Syscharsets."

/*
**Messages for "sp_cacheconfig"	18135
*/

exec sp_instmsg 18135, "The specified named cache '%1!' does not exist."
exec sp_instmsg 18136, "The cache type can only be specified once."
exec sp_instmsg 18137, "Attempt to delete the default data cache. The default cache may not be deleted."

/*
**Messages for "sp_poolconfig"	18138
*/

exec sp_instmsg 18138, "A cache name must be supplied."
exec sp_instmsg 18139, "Syntax error encountered. Parameter must be of the form 'wash = int[KMGP]'."

/*
**Messages for "sp_cacheconfig"	18140
*/

exec sp_instmsg 18140, "Cannot modify a cache type to be 'log only' when non-log objects are bound to it. Use sp_helpcache to print out bound objects and sp_unbindcache to delete the cache bindings."

/*
**Messages for "sp_poolconfig"	18141
*/

exec sp_instmsg 18141, "Syntax error encountered on size specification. %1! is an invalid size."
exec sp_instmsg 18142, "I/O size of the memory pool is expected as the third argument."
exec sp_instmsg 18143, "The source pool (%1! buffers, total size %2!) is not large enough to satisfy the request to move %3! of memory."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18144, "Source pool (%1!) and destination pool (%2!) are the same pool. The source and destination pools must be different."
exec sp_instmsg 18145, "Less memory moved than requested in cache '%1!'. Requested size = %2! Kb: from pool = %3!, to pool = %4!, actual memory moved = %5! Kb."

/*
**Messages for "sp_aux_getsize"	18146
*/

exec sp_instmsg 18146, "Syntax error encountered. Sizes must be of the form int[KMGP]. For example, a size of 5 magabytes may be specified as '5M'."

/*
**Messages for "sp_poolconfig"	18147
*/

exec sp_instmsg 18147, "Invalid buffer size of %1! encountered. Valid buffer sizes are powers of two between 2k and 16k inclusive."
exec sp_instmsg 18148, "The specified pool (%1!) does not exist in named cache '%2!'."

/*
**Messages for "sp_aux_getsize"	18149
*/

exec sp_instmsg 18149, "Invalid size of %1! encountered. Sizes must be greter than zero."

/*
**Messages for "sp_displaylevel"	18150
*/

exec sp_instmsg 18150, "The login '%1!' does not exist."
exec sp_instmsg 18151, "The current display level for login '%1!' is '%2!'."
exec sp_instmsg 18152, "Invalid display level. The valid values are 'basic', 'intermediate' or 'comprehensive'."
exec sp_instmsg 18153, "The display level for login '%1!' has been changed to '%2!'."

/*
**Messages for "sp_aux_parse_entity"	18154
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 18154, "Object '%1!' is not a table."

/*
**Messages for "sp_cacheconfig"	18155
*/

exec sp_instmsg 18155, "The cache type can be either 'logonly' or 'mixed' only."

/*
**Messages for "sp_bindcache"	18156
*/

exec sp_instmsg 18156, "Usage: sp_unbindcache dbname [, [ownername.]tablename [, indexname | 'text only' | 'table only']]"

/*
**Messages for "sp_setrepdb"	18157
*/

exec sp_instmsg 18157, "The stored procedure 'sp_setrepdb' is currently not supported."

/*
**Messages for "sp_setpglockpromote"	18158
*/

exec sp_instmsg 18158, "At least one of the parameters 'new_lwm', 'new_hwm' or 'new_pct' must be non-NULL to execute sp_setpglockpromote."
exec sp_instmsg 18159, "You must be in the 'master' database to add, change or drop lock promotion attributes for a user database."
exec sp_instmsg 18160, "Please specify a non-NULL value for '%1!', since it has not been set previously with a non-NULL value."
exec sp_instmsg 18161, "Object name parameter must be NULL for Server-wide lock promotion attributes. Using NULL instead of - '%1!'."
exec sp_instmsg 18162, "'%1!' is a not a user table. '%2!' can be used only on user tables."
exec sp_instmsg 18163, "The 'lock promotion LWM' value '%1!' cannot be greater than the 'lock promotion HWM' value '%2!'."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18164, "Invalid value specified for 'scope' parameter. Valid values are 'SERVER','DATABASE' or 'TABLE'."
exec sp_instmsg 18165, "The 'lock promotion!' attributes of '%1!', '%2!' have been changed. The new values are '%3!'."

/*
**Messages for "sp_dropglockpromote"	18166
*/

exec sp_instmsg 18166, "Lock promotion attribute does not exist for '%1!', '%2!'. Cannot delete it."
exec sp_instmsg 18167, "Lock promotion attribute of object '%1!' has been dropped."
exec sp_instmsg 18168, "Invalid value '%1!', specified for 'scope' parameter. Valid values are 'DATABASE' or 'TABLE'."
exec sp_instmsg 18169, "Server-wide lock promotion values cannot be dropped. Use 'sp_configure' to restore server-wide defaults."

/*
**Messages for "sp_bindcache"	18170
*/

exec sp_instmsg 18170, "Usage: sp_bindcache cachename, dbname [, [ownername.]tablename [, indexname | 'text only' | 'table only']]"

/*
**Messages for "sp_aux_parse_entity"	18171
*/

exec sp_instmsg 18171, "The table must have a text column if 'text only' is specified."

/*
**Messages for "sp_cacheconfig"	18172
*/

exec sp_instmsg 18172, "The change is completed. The SQL Server must be rebooted for the change to take effect."

/*
**Messages for "sp_cachestrategy"	18173
*/

exec sp_instmsg 18173, "Only the System Administrator (SA) or the Object Owner may execute this stored Procedure."

/*
**Messages for "sp_helpcache"	18174
*/

go

dump transaction master with truncate_only
go

exec sp_instmsg 18174, "The database '%1!' is offline. To obtain cache-bindings for objects in this database, please online the database and rerun sp_helpcache."

/*
**Messages for "sp_bindcache"	18175
*/

exec sp_instmsg 18175, "Specified named cache is not active yet. The SQL Server must be rebooted to activate the named cache."

/*
**Messages for "sp_cachestrategy"	18176
*/

exec sp_instmsg 18176, "Usage: sp_cachestrategy dbname, [ownername.]tablename [, indexname | 'text only' | 'table only' [, { prefetch | mru }, { 'on' | 'off'}]]"

/*
**Messages for "sp_cacheconfig"	18177
*/

exec sp_instmsg 18177, "Usage: sp_cacheconfig [ cachename [, 'cache_size[K|P|M|G]' ] [, logonly | mixed ]]"

/*
**Messages for "sp_sysmon"	18179
*/

exec sp_instmsg 18179, "Invalid parameter. Usage: sp_sysmon {1-10}"

/*
**Messages for "sp_chgattribute"	18181
*/

exec sp_instmsg 18181, "The option max_rows_per_page is not allowed on text/image objects."

/*
**Messages for "sp_poolconfig"	18339
*/

exec sp_instmsg 18339, "Could not find at least 512K space for the buffer pool '%1!'. Make sure the cache '%2!' is not in use when running sp_poolconfig."
exec sp_instmsg 18394, "The buffer pool '%1!' cannot be used until you restart SQL Server or delete the pool and retry sp_poolconfig when the cache '%2!' is not in use."

/*
**Messages for "sp_helplog"	18433
*/

exec sp_instmsg 18433, "No valid log device can be found to contain the starting logpage of '%1!', on database '%2!'. Perhaps the segment mapping of database has changed recently. Please inspect the sysusages catalog and contact your system administrator."

/*
**Messages for "sp_shmdumpconfig"	18492
*/

exec sp_instmsg 18492, "Invalid dump condition type %1!"
go

dump transaction master with truncate_only
go

exec sp_instmsg 18493, "You cannot add the system default settings. Use update."
exec sp_instmsg 18494, "No value for %1! was given."
exec sp_instmsg 18495, "The maximum number of dump conditions (%1!) are already set."
exec sp_instmsg 18496, "Either drop a dump condition or increase the value of 'maximum dump conditions'."
exec sp_instmsg 18497, "No values to update were given."
exec sp_instmsg 18498, "There is already a condition of type %1!."
exec sp_instmsg 18499, "There is already a condition of type %1! and value %2!."
exec sp_instmsg 18500, "No record found for %1!."
exec sp_instmsg 18501, "No record found for %1! %2!."
exec sp_instmsg 18502, "%1! is not a valid error number."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18503, "%1! is not a valid module."
exec sp_instmsg 18504, "Severity must be between 10 and 26."
exec sp_instmsg 18505, "Notification failed. Update of condition was not performed. If this was an update operation, please drop and re-add this dump condition."
exec sp_instmsg 18506, "Insert of new record for %1! %2! failed."
exec sp_instmsg 18507, "Invalid memory mode %1!."
exec sp_instmsg 18508, "You cannot drop the system default settings."
exec sp_instmsg 18509, "There is no condition set for %1! %2!."
exec sp_instmsg 18510, "Notification failed. Your change did not take affect."
exec sp_instmsg 18511, "Error reading sysattributes table."
exec sp_instmsg 18512, "WARNING: Unknown dump condition record type found: %1!."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18513, "Current number of conditions: %1!"
exec sp_instmsg 18514, "Maximum number of conditions: %1!"
exec sp_instmsg 18515, "Printing Debug Information:"
exec sp_instmsg 18516, "Invalid action: %1!"
exec sp_instmsg 18517, "Dump count reset for %1! %2!."
exec sp_instmsg 18518, "You cannot reset the dump count for the default setting."
exec sp_instmsg 18519, "The maxdumps parameter value must be greater than zero."
exec sp_instmsg 18536, "The @value parameter must be NULL when setting system defaults."

/*
**Messages for "sp_poolconfig"	18550
*/

exec sp_instmsg 18550, "The '%1!' pool in cache '%2!' became smaller than the required minimum pool size of 512K as a result of this operation. To delete the pool, restart SQL Server or retry sp_poolconfig when the cache is not in use."
exec sp_instmsg 18558, "Unable to delete the '%1!' pool in cache '%2!'."
go

dump transaction master with truncate_only
go

exec sp_instmsg 18559, "This pool has been marked unavailable. You can remove it completely by retrying sp_poolconfig when the cache is not in use or by restarting the Server."
exec sp_instmsg 18560, "Unable to move '%1!' from the '%2!' pool to the '%3!' pool in cache '%4!'. Only '%5!' moved."
exec sp_instmsg 18561, "The '%1!' pool has been marked unavailable, since it is smaller than the minimum pool size of 512KB."
exec sp_instmsg 18562, "You can size the pools correctly by retrying sp_poolconfig when the cache is not in use or by restarting the Server."
go


drop PROC sp_instmsg
go

dump transaction master with truncate_only
go

set nocount off
go

go
/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

use master
go

delete spt_values
	where type = "W"
go
insert spt_values (name, number, type) values ("add",   1 , "W")
insert spt_values (name, number, type) values ("all",   2 , "W")
insert spt_values (name, number, type) values ("alter",   3 , "W")
insert spt_values (name, number, type) values ("and",   4 , "W")
insert spt_values (name, number, type) values ("any",   5 , "W")
insert spt_values (name, number, type) values ("arith_overflow",   6 , "W")
insert spt_values (name, number, type) values ("as",   7 , "W")
insert spt_values (name, number, type) values ("asc",   8 , "W")
insert spt_values (name, number, type) values ("at",   9 , "W")
insert spt_values (name, number, type) values ("authorization",  10 , "W")
insert spt_values (name, number, type) values ("avg",  11 , "W")
insert spt_values (name, number, type) values ("begin",  12 , "W")
insert spt_values (name, number, type) values ("between",  13 , "W")
insert spt_values (name, number, type) values ("break",  14 , "W")
insert spt_values (name, number, type) values ("browse",  15 , "W")
insert spt_values (name, number, type) values ("bulk",  16 , "W")
insert spt_values (name, number, type) values ("by",  17 , "W")
insert spt_values (name, number, type) values ("cascade",  18 , "W")
insert spt_values (name, number, type) values ("char_convert",  19 , "W")
insert spt_values (name, number, type) values ("check",  20 , "W")
insert spt_values (name, number, type) values ("checkpoint",  21 , "W")
go
insert spt_values (name, number, type) values ("close",  22 , "W")
insert spt_values (name, number, type) values ("clustered",  23 , "W")
insert spt_values (name, number, type) values ("commit",  24 , "W")
insert spt_values (name, number, type) values ("compute",  25 , "W")
insert spt_values (name, number, type) values ("confirm",  26 , "W")
insert spt_values (name, number, type) values ("constraint",  27 , "W")
insert spt_values (name, number, type) values ("continue",  28 , "W")
insert spt_values (name, number, type) values ("controlrow",  29 , "W")
insert spt_values (name, number, type) values ("convert",  30 , "W")
insert spt_values (name, number, type) values ("count",  31 , "W")
insert spt_values (name, number, type) values ("create",  32 , "W")
insert spt_values (name, number, type) values ("current",  33 , "W")
insert spt_values (name, number, type) values ("cursor",  34 , "W")
insert spt_values (name, number, type) values ("data_pgs",  35 , "W")
insert spt_values (name, number, type) values ("database",  36 , "W")
insert spt_values (name, number, type) values ("dbcc",  37 , "W")
insert spt_values (name, number, type) values ("deallocate",  38 , "W")
insert spt_values (name, number, type) values ("declare",  39 , "W")
insert spt_values (name, number, type) values ("default",  40 , "W")
insert spt_values (name, number, type) values ("delete",  41 , "W")
go
insert spt_values (name, number, type) values ("desc",  42 , "W")
insert spt_values (name, number, type) values ("disk",  43 , "W")
insert spt_values (name, number, type) values ("distinct",  44 , "W")
insert spt_values (name, number, type) values ("double",  45 , "W")
insert spt_values (name, number, type) values ("drop",  46 , "W")
insert spt_values (name, number, type) values ("dummy",  47 , "W")
insert spt_values (name, number, type) values ("dump",  48 , "W")
insert spt_values (name, number, type) values ("else",  49 , "W")
insert spt_values (name, number, type) values ("end",  50 , "W")
insert spt_values (name, number, type) values ("endtran",  51 , "W")
insert spt_values (name, number, type) values ("errlvl",  52 , "W")
insert spt_values (name, number, type) values ("errordata",  53 , "W")
insert spt_values (name, number, type) values ("errorexit",  54 , "W")
insert spt_values (name, number, type) values ("escape",  55 , "W")
insert spt_values (name, number, type) values ("except",  56 , "W")
insert spt_values (name, number, type) values ("exec",  57 , "W")
insert spt_values (name, number, type) values ("execute",  58 , "W")
insert spt_values (name, number, type) values ("exists",  59 , "W")
insert spt_values (name, number, type) values ("exit",  60 , "W")
insert spt_values (name, number, type) values ("fetch",  61 , "W")
insert spt_values (name, number, type) values ("fillfactor",  62 , "W")
go
insert spt_values (name, number, type) values ("for",  63 , "W")
insert spt_values (name, number, type) values ("foreign",  64 , "W")
insert spt_values (name, number, type) values ("from",  65 , "W")
insert spt_values (name, number, type) values ("goto",  66 , "W")
insert spt_values (name, number, type) values ("grant",  67 , "W")
insert spt_values (name, number, type) values ("group",  68 , "W")
insert spt_values (name, number, type) values ("having",  69 , "W")
insert spt_values (name, number, type) values ("holdlock",  70 , "W")
insert spt_values (name, number, type) values ("identity",  71 , "W")
insert spt_values (name, number, type) values ("identity_insert",  72 , "W")
insert spt_values (name, number, type) values ("if",  73 , "W")
insert spt_values (name, number, type) values ("in",  74 , "W")
insert spt_values (name, number, type) values ("index",  75 , "W")
insert spt_values (name, number, type) values ("insert",  76 , "W")
insert spt_values (name, number, type) values ("intersect",  77 , "W")
insert spt_values (name, number, type) values ("into",  78 , "W")
insert spt_values (name, number, type) values ("is",  79 , "W")
insert spt_values (name, number, type) values ("isolation",  80 , "W")
insert spt_values (name, number, type) values ("key",  81 , "W")
insert spt_values (name, number, type) values ("kill",  82 , "W")
go
insert spt_values (name, number, type) values ("level",  83 , "W")
insert spt_values (name, number, type) values ("like",  84 , "W")
insert spt_values (name, number, type) values ("lineno",  85 , "W")
insert spt_values (name, number, type) values ("load",  86 , "W")
insert spt_values (name, number, type) values ("max",  87 , "W")
insert spt_values (name, number, type) values ("max_rows_per_page",  88 , "W")
insert spt_values (name, number, type) values ("min",  89 , "W")
insert spt_values (name, number, type) values ("mirror",  90 , "W")
insert spt_values (name, number, type) values ("mirrorexit",  91 , "W")
insert spt_values (name, number, type) values ("national",  92 , "W")
insert spt_values (name, number, type) values ("noholdlock",  93 , "W")
insert spt_values (name, number, type) values ("nonclustered",  94 , "W")
insert spt_values (name, number, type) values ("not",  95 , "W")
insert spt_values (name, number, type) values ("null",  96 , "W")
insert spt_values (name, number, type) values ("numeric_truncation",  97 , "W")
insert spt_values (name, number, type) values ("of",  98 , "W")
insert spt_values (name, number, type) values ("off",  99 , "W")
insert spt_values (name, number, type) values ("offsets",  100 , "W")
insert spt_values (name, number, type) values ("on",  101 , "W")
insert spt_values (name, number, type) values ("once", 102 , "W")
insert spt_values (name, number, type) values ("online",  103 , "W")
insert spt_values (name, number, type) values ("only", 104 , "W")
go
insert spt_values (name, number, type) values ("open", 105 , "W")
insert spt_values (name, number, type) values ("option", 106 , "W")
insert spt_values (name, number, type) values ("or", 107 , "W")
insert spt_values (name, number, type) values ("order", 108 , "W")
insert spt_values (name, number, type) values ("over", 109 , "W")
insert spt_values (name, number, type) values ("partition", 110 , "W")
insert spt_values (name, number, type) values ("perm", 111 , "W")
insert spt_values (name, number, type) values ("permanent", 112 , "W")
insert spt_values (name, number, type) values ("plan", 113 , "W")
insert spt_values (name, number, type) values ("precision", 114 , "W")
insert spt_values (name, number, type) values ("prepare", 115 , "W")
insert spt_values (name, number, type) values ("primary", 116 , "W")
insert spt_values (name, number, type) values ("print", 117 , "W")
insert spt_values (name, number, type) values ("privileges", 118 , "W")
insert spt_values (name, number, type) values ("proc", 119 , "W")
insert spt_values (name, number, type) values ("procedure", 120 , "W")
insert spt_values (name, number, type) values ("processexit", 121 , "W")
insert spt_values (name, number, type) values ("public", 122 , "W")
insert spt_values (name, number, type) values ("raiserror", 123 , "W")
insert spt_values (name, number, type) values ("read", 124 , "W")
insert spt_values (name, number, type) values ("readtext", 125 , "W")
go
insert spt_values (name, number, type) values ("reconfigure", 126 , "W")
insert spt_values (name, number, type) values ("references", 127 , "W")
insert spt_values (name, number, type) values ("replace", 128 , "W")
insert spt_values (name, number, type) values ("reserved_pgs", 129 , "W")
insert spt_values (name, number, type) values ("return", 130 , "W")
insert spt_values (name, number, type) values ("revoke", 131 , "W")
insert spt_values (name, number, type) values ("role", 132 , "W")
insert spt_values (name, number, type) values ("rollback", 133 , "W")
insert spt_values (name, number, type) values ("rowcnt", 134 , "W")
insert spt_values (name, number, type) values ("rowcount", 135 , "W")
insert spt_values (name, number, type) values ("rows", 136 , "W")
insert spt_values (name, number, type) values ("rule", 137 , "W")
insert spt_values (name, number, type) values ("save", 138 , "W")
insert spt_values (name, number, type) values ("schema", 139 , "W")
insert spt_values (name, number, type) values ("select", 140 , "W")
insert spt_values (name, number, type) values ("set", 141 , "W")
insert spt_values (name, number, type) values ("setuser", 142 , "W")
insert spt_values (name, number, type) values ("shared", 143 , "W")
insert spt_values (name, number, type) values ("shutdown", 144 , "W")
insert spt_values (name, number, type) values ("some", 145 , "W")
go
insert spt_values (name, number, type) values ("statistics", 146 , "W")
insert spt_values (name, number, type) values ("stripe", 147 , "W")
insert spt_values (name, number, type) values ("sum", 148 , "W")
insert spt_values (name, number, type) values ("syb_identity", 149 , "W")
insert spt_values (name, number, type) values ("syb_restree", 150 , "W")
insert spt_values (name, number, type) values ("syb_terminate", 151 , "W")
insert spt_values (name, number, type) values ("table", 152 , "W")
insert spt_values (name, number, type) values ("temp", 153 , "W")
insert spt_values (name, number, type) values ("temporary", 154 , "W")
insert spt_values (name, number, type) values ("textsize", 155 , "W")
insert spt_values (name, number, type) values ("to", 156 , "W")
insert spt_values (name, number, type) values ("tran", 157 , "W")
insert spt_values (name, number, type) values ("transaction", 158 , "W")
insert spt_values (name, number, type) values ("trigger", 159 , "W")
insert spt_values (name, number, type) values ("truncate", 160 , "W")
insert spt_values (name, number, type) values ("tsequal", 161 , "W")
insert spt_values (name, number, type) values ("union", 162 , "W")
insert spt_values (name, number, type) values ("unique", 163 , "W")
insert spt_values (name, number, type) values ("unpartition", 164 , "W")
insert spt_values (name, number, type) values ("update", 165 , "W")
insert spt_values (name, number, type) values ("use", 166 , "W")
insert spt_values (name, number, type) values ("used_pgs", 167 , "W")
go
insert spt_values (name, number, type) values ("user", 168 , "W")
insert spt_values (name, number, type) values ("user_option", 169 , "W")
insert spt_values (name, number, type) values ("using", 170 , "W")
insert spt_values (name, number, type) values ("values", 171 , "W")
insert spt_values (name, number, type) values ("varying", 172 , "W")
insert spt_values (name, number, type) values ("view", 173 , "W")
insert spt_values (name, number, type) values ("waitfor", 174 , "W")
insert spt_values (name, number, type) values ("where", 175 , "W")
insert spt_values (name, number, type) values ("while", 176 , "W")
insert spt_values (name, number, type) values ("with", 177 , "W")
insert spt_values (name, number, type) values ("work", 178 , "W")
insert spt_values (name, number, type) values ("writetext", 179 , "W")
go
/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** This file creates the tables needed for the Microsoft stored procedures.
** It also loads the needed values into those tables.
** The tables are:
**	spt_datatype_info_ext
**	spt_datatype_info
**	spt_server_info
**
** Under no circumstances should changes be made to the tables stored in
** this routine unless they are to fix problems with ODBC connectivity.
** These tables interface with the ODBC connectivity routines:
**	sp_columns
**	sp_datatype_info
**
** In addition, any changes made to this file will require the Sybase SQL
** server to be recertified as ODBC compliant by the certification group
** at Sybase (current name is "Interoperability Engineering Technology
** Solutions Group").
*/



/*
** spt_datatype_info_ext
*/

if (exists (select * from sysobjects
		where name = 'spt_datatype_info_ext' and type = 'U'))
    drop table spt_datatype_info_ext
go
create table spt_datatype_info_ext 
(
	user_type	smallint  not null, 
	create_params	varchar(32) null
)
go

grant select on spt_datatype_info_ext to public
go


insert into spt_datatype_info_ext
	/* CHAR 	 user_type, create_params */
	values			 (1, "length" )

insert into spt_datatype_info_ext
	/* VARCHAR	 user_type, create_params */
	values			 (2, "max length" )

insert into spt_datatype_info_ext
	/* BINARY	 user_type, create_params */
	values			 (3, "length" )

insert into spt_datatype_info_ext
	/* VARBINARY	 user_type, create_params */
	values			 (4, "max length" )

insert into spt_datatype_info_ext
	/* NUMERIC	 usertype, create_params */
	values			 (10, "precision,scale" )

insert into spt_datatype_info_ext
	/* SYSNAME	 user_type, create_params */
	values			 (18, "max length" )

insert into spt_datatype_info_ext
	/* DECIMAL	 usertype, create_params */
	values			 (26, "precision,scale" )
go

/* 
** spt_datatype_info
*/
if (exists (select * from sysobjects
		where name = 'spt_datatype_info' and type = 'U'))
    drop table spt_datatype_info
go
create table spt_datatype_info 
(
	ss_dtype	   tinyint	not null, 
	type_name          varchar(32)  not null, 
	data_type          smallint     not null, 
	data_precision     int          null, 
	numeric_scale      smallint     null, 
	numeric_radix      smallint     null, 
	length             int          null, 
	literal_prefix     varchar(32)  null, 
	literal_suffix     varchar(32)  null, 
	create_params      varchar(32)  null, 
	nullable           smallint     not null, 
	case_sensitive     smallint     not null, 
	searchable         smallint     not null, 
	unsigned_attribute smallint     null, 
	money              smallint     not null, 
	auto_increment     smallint     null, 
	local_type_name    varchar(128) not null, 
	aux                int          null
)
go

grant select on spt_datatype_info to public
go

/*
**	There is a complicated set of SQL used to deal with
**	the SQL Server Null data types (MONEYn, INTn, etc.)
**	ISNULL is the only conditional SQL Server function that can be used
**	to differentiate between these types depending on size.
**
**	The aux column in the above table is used to differentiate
**	the null data types from the non-null types.
**
**	The aux column contains NULL for the null data types and 0
**	for the non-null data types.
**
**	The following SQL returns the contents of the aux column (0)
**	for the non-null data types and returns a variable non-zero
**	value for the null data types.
**
**			 " I   I I FFMMDD"
**			 " 1   2 4 484848"
**	isnull(d.aux, ascii(substring("666AAA@@@CB??GG", 
**	2*(d.ss_dtype%35+1)+2-8/c.length, 1))-60)
**
**	The '2*(d.ss_dtype%35+1)+2-8/c.length' selects a specific character of
**	the substring mask depending on the null data type and its size, i.e.
**	null MONEY4 or null MONEY8.  The character selected is then converted
**	to its binary value and an appropriate bias (i.e. 60) is subtracted to
**	return the correct non-zero value.	This value may be used as a
**	constant, i.e. ODBC data type, precision, scale, etc., or used as an
**	index with a substring to pick out a character string, i.e. type name.
**
**	The comments above the substring mask denote which character is
**	selected for each null data type, i.e. In (INTn), Fn (FLOATn), 
**	Mn (MONEYn) and Dn (DATETIMn).
*/


declare @case smallint

select @case = 0
select @case = 1 where 'a' != 'A'

/* Local Binary */
insert into spt_datatype_info values
/* ss_type, name, data_type, prec, scale, rdx, len, prf, suf, 
** cp, nul, case, srch, unsigned, money, auto, local, aux 
*/
(45, "binary", -2, null, null, null, null, "0x", null, 
	"length", 1, 0, 2, null, 0, null, "binary", 0)

/* Local Bit */
insert into spt_datatype_info values
(50, "bit", -7, 1, 0, 2, null, null, null, 
 null, 0, 0, 2, null, 0, null, "bit", 0)

/* Local Char */
insert into spt_datatype_info values
(47, "char", 1, null, null, null, null, "'", "'", 
"length", 1, @case, 3, null, 0, null, "char", 0)

/* Local Datetime */
insert into spt_datatype_info values
(61, "datetime", 11, 23, 3, 10, 16, "'", "'", 
 null, 1, 0, 3, null, 0, null, "datetime", 0)

/* Local Smalldatetime */
insert into spt_datatype_info values
(58, "smalldatetime", 11, 16, 0, 10, 16, "'", "'", 
null, 1, 0, 3, null, 0, null, "smalldatetime", 0)

/* Local Datetimn  sql server type is "datetimn" */
insert into spt_datatype_info values
(111, "smalldatetime", 0, 0, 0, 10, 0, "'", "'", 
null, 1, 0, 3, null, 0, null, "datetime", null)

/* Decimal sql server type is "decimal" */
insert into spt_datatype_info values
(55, "decimal", 3, 38, 0, 10, 0, null, null,
"precision,scale", 1, 0, 2, 0, 0, 0, "decimal", 0)

/* Numeric sql server type is "numeric" */
insert into spt_datatype_info values
(63, "numeric", 2, 38, 0, 10, 0, null, null,
"precision,scale", 1, 0, 2, 0, 0, 0, "numeric", 0)

/* Local Float */
insert into spt_datatype_info values
(62, "float", 6, 15, null, 10, null, null, null, 
null, 1, 0, 2, 0, 0, 0, "float", 0)

/* Local RealFloat   sql server type is "floatn" */
insert into spt_datatype_info values
(109, "float        real", 0, 0, null, 10, 0, null, null, 
null, 1, 0, 2, 0, 0, 0, "real      float", null)

/* Local Real */
insert into spt_datatype_info values
(59, "real", 7, 7, null, 10, null, null, null,
null, 1, 0, 2, 0, 0, 0, "real", 0)

/* Local Smallmoney */
insert into spt_datatype_info values
(122, "smallmoney", 3, 10, 4, 10, null, "$", null, 
null, 1, 0, 2, 0, 1, 0, "smallmoney", 0)

/* Local Int */
insert into spt_datatype_info values
(56, "int", 4, 10, 0, 10, null, null, null, 
null, 1, 0, 2, 0, 0, 0, "int", 0)

/* Local Intn  sql server type is "intn" */
insert into spt_datatype_info values
(38, "smallint     tinyint", 0, 0, 0, 10, 0, null, null, 
null, 1, 0, 2, 0, 0, 0, "tinyint   smallint", null)

/* Local Money */
insert into spt_datatype_info values
(60, "money", 3, 19, 4, 10, null, "$", null, 
null, 1, 0, 2, 0, 1, 0, "money", 0)

/* Local Moneyn  sql server type is "moneyn" */
insert into spt_datatype_info values
(110, "smallmoney", 0, 0, 4, 10, 0, "$", null, 
null, 1, 0, 2, 0, 1, 0, "smallmoneymoney", null)

/* Local Smallint */
insert into spt_datatype_info values
(52, "smallint", 5, 5, 0, 10, null, null, null, 
null, 1, 0, 2, 0, 0, 0, "smallint", 0)

/* Local Text */
insert into spt_datatype_info values
(35, "text", -1, 2147483647, null, null, 2147483647, "'", "'", 
null, 1, @case, 1, null, 0, null, "text", 0)

/* Local Varbinary */
insert into spt_datatype_info values
(37, "varbinary", -3, null, null, null, null, "0x", null, 
"max length", 1, 0, 2, null, 0, null, "varbinary", 0)

/* Local Tinyint */
insert into spt_datatype_info values
(48, "tinyint", -6, 3, 0, 10, null, null, null, 
null, 1, 0, 2, 1, 0, 0, "tinyint", 0)

/* Local Varchar */
insert into spt_datatype_info values
(39, "varchar", 12, null, null, null, null, "'", "'", 
"max length", 1, @case, 3, null, 0, null, "varchar", 0)

/* Local Image */
insert into spt_datatype_info values
(34, "image", -4, 2147483647, null, null, 2147483647, "0x", null, 
null, 1, 0, 1, null, 0, null, "image", 0)
go



dump tran master with truncate_only
go

/*
** spt_server_info
*/
if (exists (select * from sysobjects
		where name = 'spt_server_info' and type = 'U'))
    drop table spt_server_info
go
create table spt_server_info (
	  attribute_id		int, 
	  attribute_name	varchar(60), 
	  attribute_value	varchar(255))
go

insert into spt_server_info
	values (1, "DBMS_NAME", "SQL Server")
insert into spt_server_info
	values (2, "DBMS_VER", @@version)
insert into spt_server_info
	values (6, "DBE_NAME", "")
insert into spt_server_info
	values (10, "OWNER_TERM", "owner")
insert into spt_server_info
	values (11, "TABLE_TERM", "table")
insert into spt_server_info
	values (12, "MAX_OWNER_NAME_LENGTH", "30")
insert into spt_server_info
	values (16, "IDENTIFIER_CASE", "MIXED")
insert into spt_server_info
	values (15, "COLUMN_LENGTH", "30")
insert into spt_server_info
	values (13, "TABLE_LENGTH", "30")
insert into spt_server_info
	values (100, "USERID_LENGTH", "30")
insert into spt_server_info
	values (17, "TX_ISOLATION", "2")
insert into spt_server_info
	values (18, "COLLATION_SEQ", "")
insert into spt_server_info
	values (14, "MAX_QUAL_LENGTH", "30")
insert into spt_server_info
	values (101, "QUALIFIER_TERM", "database")
insert into spt_server_info
	values (19, "SAVEPOINT_SUPPORT", "Y")
insert into spt_server_info
	values (20, "MULTI_RESULT_SETS", "Y")
insert into spt_server_info
	values (102, "NAMED_TRANSACTIONS", "Y")
insert into spt_server_info
	values (103, "SPROC_AS_LANGUAGE", "Y")
insert into spt_server_info
	values (103, "REMOTE_SPROC", "Y")
insert into spt_server_info
	values (22, "ACCESSIBLE_TABLES", "Y")
insert into spt_server_info
	values (104, "ACCESSIBLE_SPROC", "Y")
insert into spt_server_info
	values (105, "MAX_INDEX_COLS", "16")
insert into spt_server_info
	values (106, "RENAME_TABLE", "Y")
insert into spt_server_info
	values (107, "RENAME_COLUMN", "Y")
insert into spt_server_info
	values (108, "DROP_COLUMN", "Y")
insert into spt_server_info
	values (109, "INCREASE_COLUMN_LENGTH", "N")
insert into spt_server_info
	values (110, "DDL_IN_TRANSACTION", "Y")
insert into spt_server_info
	values (111, "DESCENDING_INDEXES", "N")
insert into spt_server_info
	values (112, "SP_RENAME", "Y")
go
/*
** NOTE: the following applies to Microsoft changes, not Sybase.  Do not change
** for Sybase check-ins unless we are synchronizing with Microsoft changes.
**
** The last row in spt_server_info has been used as the version number of the 
** file. The convention is jj.nn.dddd, where:
** 	jj is the major version number ("01" now), 
**	nn is the minor version number ("01" now), and 
**	dddd is the date in the form of month and day (mmdd) of the date you 
**	check in this file.  Add (current year-1991)*12 to the month to keep 
**	in sync with the driver version numbers.  Checking in on Feb 5 1993
**	would mean setting the value to 01.01.2605.
**
*/
insert into spt_server_info
	values (500, "SYS_SPROC_VERSION", "01.01.2822")
go
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_procxmode')
begin
	drop procedure sp_procxmode
end
go
print "Installing sp_procxmode"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure sp_procxmode
@procname varchar(255) = null,
@tranmode varchar(30) = null
as

declare @uid smallint
declare @oid int
declare @msg varchar(250)	/* message text */

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* If either parameter is null we will be joining with a temporary table
** to convert transaction mode numbers (0, 1, 2) to strings ("Unchained",
** "Chained", "Any Mode").
*/
if ((@procname is null) or (@tranmode is null))
begin
	create table #tranmode (intval integer, charval varchar(15))
	insert into #tranmode values(0, "Unchained")
	insert into #tranmode values(1, "Chained")
	insert into #tranmode values(2, "Any Mode")
end

/* If the first parameter is null, we're to report the transaction-modes
** of every stored procedure in the current database.
*/
if (@procname is null)
begin
	select "procedure name" = o.name, "user name" = user_name(o.uid),
		"transaction mode" = t.charval 
	from sysobjects o, #tranmode t
	where (o.type = "P") and (t.intval = ((o.sysstat2 / 16) & 3))
	order by o.name

	return(0)
end

/* If only the second parameter is null, we're to report the
** transaction-mode of the specified stored procedure.
*/
if ((@procname is not  null) and (@tranmode is null))
begin
	select "procedure name" = o.name, "user name" = user_name(o.uid),
		"transaction mode" = t.charval
	from sysobjects o, #tranmode t
	where (o.type = "P") and (@procname = o.name) and
		(t.intval = ((o.sysstat2 / 16) & 3))

	return(0)
end

/* If neither parameter is null, we're to set the transaction-mode
** of the specified procedure to the specified value.
*/
if ((@procname is not  null) and (@tranmode is not  null))
begin
	/*
	** Update transaction-mode in both sysobjects and DES.
	*/
	dbcc update_tmode(@procname, @tranmode)

	return(0) 
end
go
exec sp_procxmode 'sp_procxmode', 'anymode'
go
grant execute on sp_procxmode to public
go
dump tran master with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_validlang')
begin
	drop procedure sp_validlang
end
go
print "Installing sp_validlang"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */
create procedure sp_validlang
@name	varchar(30)
as


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* Check to see if this language is in Syslanguages. */
if exists (select *
		from master.dbo.syslanguages
		where name = @name)
begin
	return 0
end
return 1
go
exec sp_procxmode 'sp_validlang', 'anymode'
go
grant execute on sp_validlang to public
go
dump tran master with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_getmessage')
begin
	drop procedure sp_getmessage
end
go
print "Installing sp_getmessage"
go


/* generic/sproc/getmessage	14.2	4/25/91 */

/* Messages from sysmessages
** 17200, "Message number must be greater than or equal to 17000."
** 17201, "'%1!' is not an official language name from Syslanguages."
** 17202, "Message number %1! does not exist in the %2! language."
*/

create procedure sp_getmessage
@message_num int,
@result varchar(255) output,
@language varchar(30) = NULL
as

	declare @lang_id smallint 
	declare @msg varchar(255)
	declare @returncode smallint

	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	/* 
	** Use default language if none specified, 
	** and initialize result 
	*/
	select @lang_id = @@langid, @result = NULL

	/* Only retrieve external errors */
	if @message_num < 17000
	BEGIN
 		/* 17200   "Message number must be greater than or equal to 17000." */
		 select @msg = description from master.dbo.sysmessages
				    where error = 17200
		 print @msg
		 return (1)
	END

	/*
	** Check that language is valid.
	*/
	if @language is not NULL
	BEGIN
	    execute @returncode = sp_validlang @language
	    if @returncode != 0
	    begin
		    /* Us_english is always valid */
		    if @language != "us_english"
		    BEGIN
			    /* 
			    ** 17201, "'%1!' is not an official language
			    **	name from Syslanguages."
			    */
			    select @msg = description from master.dbo.sysmessages
						where error = 17201
						and langid = @@langid

			    /* Get english if the current language is missing */
			    if @msg is null
				select @msg = description from master.dbo.sysmessages
						where error = 17201
						and langid is NULL

			    print @msg, @language
			    return @returncode
		    END

		    /* set to us_english */
		    select @lang_id = NULL
	    end

	    else
	    select @lang_id = langid from master.dbo.syslanguages
			where @language = name

	END

	/* The langid is assigned 0 since it gets its value from @@langid. */
	/* For us_english, we have to insert it as NULL and not 0, this is */
	/* to maintain compatibility with the current conventions          */
	if @lang_id = 0 
	begin 
		select @lang_id = NULL        
	end   

	/* Get message from the proper place */
	/* System messages */
	if @message_num < 20000
	BEGIN
		select @result = description from master.dbo.sysmessages
			   where  langid = @lang_id 
			     and   error = @message_num 

		/* Get english if the current language is missing */
		if @result is null
			select @result = description from master.dbo.sysmessages
                                        where error = @message_num
                                        and (langid is NULL or langid =0)
	END
	else
	/* User messages */
	BEGIN
		/* There is no proper alternate language for user messages */
		select @result = description from sysusermessages
			   where  langid = @lang_id 
			     and   error = @message_num 

		/* this is in here for compatibility with older revs which */
		/* by mistake used to add langid as 0 in sysusermessages   */
		if @result is null and @lang_id is NULL
			select @result = description from sysusermessages
					where (langid is NULL or langid =0)
					and error = @message_num

	END

	/* Warn the user if the message can't be found */
	if @result is null
	begin
		/* 17202, "Message number %1! does not exist in the %2! language." */
		select @msg = description from master.dbo.sysmessages
			where error = 17202
			and langid = @@langid

		if @language is null
			select @language = @@language

		if @msg is null
			select @msg = "Message number %1! does not exist in the %2! language."

		print @msg, @message_num, @language

		return (1)
	end

return (0)
go
exec sp_procxmode 'sp_getmessage', 'anymode'
go
grant execute on sp_getmessage to public
go
dump tran master with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_configure')
begin
	drop procedure sp_configure
end
go
print "Installing sp_configure"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/configure */

/*
** Messages for "sp_configure"          17410
**      Must use "langid" when referencing spt_values
**
** 17260, "Can't run %1! from within a transaction." 
** 17410, "Configuration option doesn't exist."
** 17411, "Configuration option is not unique."
** 17413, "The value of the 'number of devices' must be greater than the highest VDEVNO, '%1!', defined in sysdevices."
** 17414, "You can't set the default language to a language ID that is not defined in Syslanguages."
** 17415, "Configuration option value is not legal."
** 17418, "'%1!' is an invalid file command. The valid commands are 'verify', 'read', 'write', and 'restore'."
** 17419, "Configuration option changed. The SQL Server need not be rebooted since the option is dynamic.
** 18123, "Configuration option changed. The SQL Server must be rebooted before the change in effect since the option is static."
** 18124, "No matching configuration options.  Here is a listing of groups:"
** 18125, "Must provide the parameter 'filename'."
** 18133, "The character set, '%1!', is invalid since it is not defined in Syscharsets."
** 18134, "The sortorder, '%1!', is invalid since it is not defined in Syscharsets."
*/

create procedure sp_configure
@configname varchar(80) = NULL,		/* configure option name */
@configvalue int = NULL,		/* configure value */
@configvalue2 varchar(255) = NULL,	/* config file command/charset info */
@configvalue3 varchar(255) = NULL	/* physical name of file */
as

declare @confignum int			/* number of option to be configured */
declare @configcount int		/* number of options like @configname */
declare @whichone	int		/* using english or default lang ? */
declare @cmd		smallint	/* configuration file command */
declare @status int			/* return status for misc calls */
declare @children int			/* number of children in a group */
declare @parent int			/* config number of parent group */
declare @msg varchar(255)		/* temp buffer for messages */
declare @sysconfig smallint		/* contents of sysconfigures.config */
declare @sysname varchar(255)		/* contents of sysconfigures.comment */
declare @sysparent smallint		/* contents of sysconfigures.parent */
declare @sysstatus smallint		/* contents of sysconfigures.status */
declare @value int 			/* default charset/sort order id */
declare @user_displaylevel int		/* user display level */
declare @maxvdevno int			/* highest number of vdevno */
declare @sortorder_id int		/* current sortorder id */
declare @charset_id int			/* current charset id */
declare @sortorder_desc varchar(255)	/* description of the default sort order */
declare @use_wildcard tinyint		/* use wildcard to search option name or not */
declare @match_count int		/* number of option found by name match*/

select @whichone = 0
select @status = 0
select @cmd = 1
select @value = NULL
select @user_displaylevel = NULL
select @sortorder_id =
	value from master.dbo.syscurconfigs where config = 123
select @charset_id =
	value from master.dbo.syscurconfigs where config = 131
select @sortorder_desc =
	description from master.dbo.syscharsets 
	where id = @sortorder_id and csid = @charset_id

select @use_wildcard = 1
/*
**  Disallow running sp_configure within a transaction since it might make
**  recovery impossible.
*/
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_configure"
        return (1)
end
else
begin
        set chained off
end

set transaction isolation level 1

set nocount on

/*
**	If the "default sortorder" is case insensitive dictionary sort order,
** the procedure will just print out all the options and their values 
** without grouping if no option name is given.
*/
if (@sortorder_desc like "%" + "case-insensitive dictionary" + "%"
		and @configname is NULL)
	begin
               select "Parameter Name" = convert(char(30), name),
                        "Default" = convert(char(11), space(11-char_length(
                                    convert(varchar(11), defvalue)))+
                                    convert(varchar(11), defvalue)),
                        "Memory Used" = convert(char(11), space(11-char_length(
                                        convert(varchar(11), b.comment)))+
                                        convert(varchar(11), b.comment)),
                        "Config Value" =convert(char(11), space(11-char_length(
                          isnull(a.value2, convert(char(32), a.value)))) +
                          isnull(a.value2, convert(char(32), a.value))),
                        "Run Value" = convert(char(11), space(11-char_length(
                          isnull(b.value2, convert(char(32), b.value)))) +
                          isnull(b.value2, convert(char(32), b.value)))
                from master.dbo.sysconfigures a,
                        master.dbo.syscurconfigs b
                where
                        a.config *= b.config
                        and parent != 19
                        and a.config != 19
                order by name
		
		return (0)
end


/* Validate the configname if it not NULL */
if @configname is not NULL
begin
	select @configcount = count(*)
    		from master.dbo.sysconfigures
			where name like "%" + @configname + "%"
				and parent != 19

	/*
	**	If configure option is not unique and case-insensitive 
	** dictionary sort order is used, check if unique option found
	** by exact name match, if so, then disable wildcard match 
	** for searching option name.
	*/
	if @configcount > 1 and 
		@sortorder_desc like "%" + "case-insensitive dictionary" + "%"
	begin
		/* check if unique option found by exact name match */
		select @match_count = count(*)
                        from master.dbo.sysconfigures
                                where name = @configname
                                        and parent != 19
		if @match_count =1
		begin
			select @use_wildcard = 0  /* don't use wildcard */
			select @configcount = @match_count
		end
	end

	/*
	** If more than one option like @configname,
	** show the duplicates and return.
	*/
	if @configcount > 1
	begin
		/*
		** 17411, "Configuration option is not unique."
		*/
		exec sp_getmessage 17411, @msg output
		print @msg
		print ""

		select "Parameter Name" = convert(char(30), name),
			"Default" = convert(char(11), space(11-char_length(
				    convert(varchar(11), defvalue)))+
				    convert(varchar(11), defvalue)),
			"Memory Used" = convert(char(11), space(11-char_length(
				   	convert(varchar(11), b.comment)))+
				   	convert(varchar(11), b.comment)),
			"Config Value" =convert(char(11), space(11-char_length(
		 	  isnull(a.value2, convert(char(32), a.value)))) +
			  isnull(a.value2, convert(char(32), a.value))),
			"Run Value" = convert(char(11), space(11-char_length(
			  isnull(b.value2, convert(char(32), b.value)))) +
			  isnull(b.value2, convert(char(32), b.value)))
		from master.dbo.sysconfigures a,
			master.dbo.syscurconfigs b
		where 
			a.config *= b.config
			and name like "%" + @configname + "%"
			and parent != 19
			and a.config != 19
		order by name

		return (1)
	end
	
	/*
	** if it is a valid option and the @configvalue is not NULL,
	** set the option
	*/
	if (@configcount != 0) and (@configvalue is not NULL)
	begin
		/* set @confignum */
		select	@confignum = config,
			@sysstatus = status
			from master.dbo.sysconfigures
				where name like "%" + @configname + "%"
				and parent != 19
				and config != 19

		/*
		** If @configvalue2 is "default",
		** setting the value to default
		*/
		if (@configvalue2 = "default")
			select @value = 1
		else
			select @value = 0

		/*
		**  If the option name is "configuration file"
		*/
		if @confignum = 114
		begin
			/*
			** if the file command is one of the valid
			** commands.
			*/
			if ((@configvalue2 = "read") or
				(@configvalue2 = "write") or
    				(@configvalue2 = "restore") or
    				(@configvalue2 = "verify"))
			begin
				/*
				** if filename is NULL
				*/
				if (@configvalue3 is NULL)
				begin
        				exec sp_getmessage 18125, @msg output
					print @msg
         				return(1)
				end
				/*
				** Must have sa_role to run these
				** commands 
				*/
       				if (proc_role("sa_role") != 1)
				begin
         				return(1)
				end
				else
				begin
					if (@configvalue2 = "verify")
						select @cmd = 2
					else
					if (@configvalue2 = "read")
						select @cmd = 3
					else
					if (@configvalue2 = "write")
						select @cmd = 4
					else
					if (@configvalue2 = "restore")
						select @cmd = 5
				end
			end
			else
			begin
				/*
				** print the message to show the valid
				** file command
				*/
				exec sp_getmessage 17418, @msg output
				print @msg, @configvalue2
				return(1)
			end

			select @status = config_admin(@cmd,0,0,0,NULL,
						@configvalue3)

			if (@status = 1)
			begin
        			return(0)
			end
			else
			begin
				return (1)
			end
		end

		if @confignum = 123
		begin
			/* get current default charset id */
			select @value = value from
				master.dbo.sysconfigures
				where config = 131

			if @configvalue2 is not NULL
			begin
				/* validate the charset id */
				if not exists (select *
					from master..syscharsets
					where name = @configvalue2 
					and type between 1000 and 1999)

				begin
					exec sp_getmessage 18133, @msg output
					print @msg, @configvalue2
					return (1)
				end

				/* get default charset id from name */
				select @value = id
					from master..syscharsets
					where name = @configvalue2 
					and type between 1000 and 1999
			end
		end

		if @confignum = 131
		begin
			/* get current default sortord id */
			select @value = value from
				master.dbo.sysconfigures
				where config = 123

			if @configvalue2 is not NULL
			begin
				/* validate the sortord id */
				if not exists (select *
					from master..syscharsets
					where name = @configvalue2
					and type between 2000 and 2999)
				begin
					exec sp_getmessage 18134, @msg output
					print @msg, @configvalue2
					return (1)
				end

				/* get default sortorder id from name */
				select @value = id
					from master..syscharsets
					where name = @configvalue2
					and type between 2000 and 2999
			end
		end

		/*
		**  If this is the number of devices configuration
		**  parameter, we want to make sure that it's not being
		**  set to lower than the
		**  number of devices in sysdevices.
		*/
		if @confignum = 116
		begin
			/*
			** Get the default value if trying to set the
			** value to the default value
			*/
			if (@value = 1)
			begin
				select @configvalue = convert(int, defvalue)
					from master.dbo.syscurconfigs
					where config = 116
			end

			/*
			**  Get the max vdevno.
			*/
			select @maxvdevno = max(
				convert(tinyint,
					substring(convert(binary(4), d.low),
					v.low, 1)))
				from master.dbo.sysdevices d,
				master.dbo.spt_values v

			if (@configvalue <= @maxvdevno)
			begin
				exec sp_getmessage 17413, @msg output
				print @msg, @maxvdevno
				return (1)
			end
		end


		/* 
		**  If this is the number of default language, we want
		**  to make sure that the new value is a valid language
		**  id in Syslanguages.
		*/ 
		if @confignum = 124
		begin
			if not exists (select *
				from master.dbo.syslanguages
					where langid = @configvalue)   
			begin
				/* 0 is default language, us_english */
				if @configvalue != 0
				begin
					exec sp_getmessage 17414, @msg output
					print @msg
					return (1)
				end
			end
		end

		/* call config_admin() to set the new value */
		select @status = config_admin(@cmd, @confignum,
					 @configvalue, @value, NULL, NULL)

		/* if successful */
		if (@status = 1)
		begin
			/* Display the new value */
			select "Parameter Name" = convert(char(30), name),
			  "Default" = convert(char(11), space(11-char_length(
				convert(varchar(11), defvalue))) +
			  	convert(varchar(11), defvalue)),
			  "Memory Used" = convert(char(11),space(11-char_length(
			  	convert(varchar(11), c.comment))) +
			  	convert(varchar(11), c.comment)),
			  "Config Value" = convert(char(11),
				space(11-char_length(
		 	  	isnull(b.value2, convert(char(32), b.value)))) +
		 	  	isnull(b.value2, convert(char(32), b.value))),
			  "Run Value"  = convert(char(11), space(11-char_length(
			  	isnull(c.value2, convert(char(32), c.value)))) +
			  	isnull(c.value2, convert(char(32), c.value)))
			from master.dbo.sysconfigures b,
				master.dbo.syscurconfigs c
			where 
				b.config = @confignum and
				b.config *= c.config

			/*
			** print reboot message if this option is not
			** dynamic.
			*/
			select @sysstatus = @sysstatus & 8
			if @sysstatus = 8
			begin
				exec sp_getmessage 17419, @msg output
				print @msg
			end
			else
			begin
				exec sp_getmessage 18123, @msg output
				print @msg
			end

			return(0)
		end
		else
			return(1)
	end
end

/*
** @configcount=0 implies @configname is not valid
** @configname=NULL implies displaying all the parameters except for
** the parameters with the config number equal to 19 or the parent equal
** to 19 since those parameters are displayed by sp_cacheconfig.
*/
if (@configcount =0)
begin
	exec sp_getmessage 18124, @msg output
	print @msg
	select convert(char(50), name)
		from master.dbo.sysconfigures
		where config < 100
		and parent != 19
		and config != 19
		order by name
	return(1)
end
else if (@configname is NULL)
	select @configname = "Config"

/*
** retrieve the display level from sysattributes
*/
select @user_displaylevel = int_value from master.dbo.sysattributes where
	class = 4 AND
	attribute = 0 AND
	object_type = 'L' AND
	object = suser_id()

/*
** set the default display level to 10 if it is not defined in sysattributes
*/
if (@user_displaylevel = NULL)
	select @user_displaylevel = 10

/*
** 	If @use_wildcard = 0 and the default sortorder is case-insensitive 
** dictionary sort order, use exact match: name = @configname to get row, 
** otherwise use wildcard match: name like "%" + @configname + "%".
*/

if (@use_wildcard = 0 and @sortorder_desc like "%" + "case-insensitive dictionary" + "%")
	select  @confignum = config,
		@parent = config,
		@sysname = name,
        	@sysstatus = status
	from master.dbo.sysconfigures
		where name = @configname
		and config != 19
else
	select	@confignum = config, 
		@parent = config,
		@sysname = name,
		@sysstatus = status
	from master.dbo.sysconfigures
		where name like "%" + @configname + "%"
		and config != 19

select	@children = count(*)
	from master.dbo.sysconfigures
	where parent =  @confignum

if @children = 0
begin
	/* @@nestlevel is problem area if a sproc calls sp_configure */
	/* could pass in another param when recursing */
	if @@nestlevel > 1
	begin
		/* reached a leaf, notify parent */
		return(1)
	end
	else
	begin
		/* display the information of the config parameter */
		select "Parameter Name" = convert(char(30), name),
			"Default" = convert(char(11), space(11-char_length(
			  convert(varchar(11), defvalue))) +
			  convert(varchar(11), defvalue)),
			"Memory Used" = convert(char(11), space(11-char_length(
			  convert(varchar(11), c.comment))) +
			  convert(varchar(11), c.comment)),
			"Config Value" = convert(char(11), space(11-char_length(
		 	  isnull(b.value2, convert(char(32), b.value)))) +
		 	  isnull(b.value2, convert(char(32), b.value))),
			"Run Value"  = convert(char(11), space(11-char_length(
			  isnull(c.value2, convert(char(32), c.value)))) +
			  isnull(c.value2, convert(char(32), c.value)))
		from master.dbo.sysconfigures b,
			master.dbo.syscurconfigs c
		where 
			b.config *= c.config
			and name like "%" + @configname + "%"
			and b.config != 19
	end
end
else
begin
	select @msg = "Group: " + @sysname
	print ""
	print @msg
	print ""

	/* this poor guy has kids, so recurse to leaves */
	declare config_curs cursor for 
		select config, name, parent 
		from master.dbo.sysconfigures 
		where parent = @parent
		order by name

	open config_curs

	fetch config_curs into @sysconfig, @sysname, @sysparent

	while (@@sqlstatus = 0)
	begin

		execute @status = sp_configure @sysname


		if (@status = 1)
		begin
			/*
			** this guy has leaves as kids,
			** so print out the leaves with
			** display level <= @user_displaylevel
			** Note: If a config parameter has more than one
			** parent, the extra parents are stored in
			** 'sysattribures'.
			*/
			create table #configure_temp (config int)

			insert into #configure_temp
				select a.config
					from master.dbo.sysconfigures a,
					master.dbo.syscurconfigs b
					where
			  	   	   display_level <= @user_displaylevel
				   	   and parent = @parent
					   and a.config != 19
					   and a.config = b.config
		  		    union
				    select config
					from master.dbo.syscurconfigs,
					master.dbo.sysattributes
					where
			  	   	   display_level <= @user_displaylevel
					   and class = 4
					   and attribute = 1
					   and object_type = 'CP'
				   	   and int_value = @parent
					   and object = config
					   and config != 19

			if exists (select * from #configure_temp)
			begin
			 select "Parameter Name" = convert(char(30), name),
			 "Default" = convert(char(11), space(11-char_length(
				convert(varchar(11), defvalue))) +
				convert(varchar(11), defvalue)),
			 "Memory Used" = convert(char(11), space(11-char_length(
				convert(varchar(11), c.comment))) +
				convert(varchar(11), c.comment)),
			 "Config Value" = convert(char(11),space(11-char_length(
		 	 	isnull(b.value2, convert(char(32), b.value)))) +
		 	 	isnull(b.value2, convert(char(32), b.value))),
			 "Run Value"  = convert(char(11), space(11-char_length(
			 	isnull(c.value2, convert(char(32), c.value)))) +
			 	isnull(c.value2, convert(char(32), c.value)))
			 from master.dbo.sysconfigures b,
				master.dbo.syscurconfigs c
			 where b.config in
				(select config from #configure_temp)
				and b.config = c.config
			 order by name
			end

			drop table #configure_temp

			close config_curs
			deallocate cursor config_curs

			return(0)
		end
		else
		begin
			/*
			** this lucky guy has grandkids, so, continue
			*/
			fetch config_curs into 
				@sysconfig, @sysname, @sysparent

		end
	end

	close config_curs
	deallocate cursor config_curs

	return(0)
end

go


go
exec sp_procxmode 'sp_configure', 'anymode'
go
grant execute on sp_configure to public
go
dump tran master with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dboption')
begin
	drop procedure sp_dboption
end
go
print "Installing sp_dboption"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/a_values */

/*
** Messages for "sp_dboption"           17420
**      Use "langid" when looking at spt_values ???
**
** 17260, "Can't run %1! from within a transaction." 
** 17420, "Settable database options."
** 17421, "No such database -- run sp_helpdb to list databases."
** 17422, "The 'master' database's options can not be changed."
** 17423, "Usage: sp_dboption [dbname, optname, {true | false}]"
** 17424, "Database option doesn't exist or can't be set by user."
** 17425, "Run sp_dboption with no parameters to see options."
** 17426, "Database option is not unique."
** 17428, "You must be in the 'master' database in order to change
**	database options."                                
** 17429, "The database is currently in use -- 'read only' option
**	disallowed."                                       
** 17430, "Run the CHECKPOINT command in the database that was changed."
** 17431, "true"
** 17432, "false"
** 17433, "Database option '%1!' turned ON for database '%2!'."
** 17434, "Database option '%1!' turned OFF for database '%2!'."
** 17289, "Set your curwrite to the hurdle of current database."
** 17436, "The 'single user' option is not valid for the 'tempdb'
**	database."
*/

create procedure sp_dboption
@dbname varchar(30) = NULL,		/* database name to change */
@optname varchar(20) = NULL,		/* option name to turn on/off */
@optvalue varchar(10) = NULL		/* true or false */
as

declare @dbid int			/* dbid of the database */
declare @dbuid int			/* id of the owner of the database */
declare @statvalue smallint,		/* number of option */
	@stattype char(2),		/* status field flag */
	@statopt smallint,		/* option mask, part 1 */
	@stat2opt smallint		/* option mask, part 2 */
declare @optcount int			/* number of options like @optname */
declare @success_msg varchar(255)	/* success status message */
declare @msg varchar(250)
declare @sptlang	int
declare @true		varchar(10)
declare @false		varchar(10)
declare @whichone	int		/* which language? */
declare @name		varchar(30)
declare	@optmsgnum	int		/* identify one msgnum to compare */
declare	@msgcnt		int		/* count distinct dups */



if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @sptlang = @@langid,  @whichone = 0

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17050 and 17069
		and langid = @@langid)
	select @sptlang = 0
end


/*
**  If no @dbname given, just list the possible dboptions.
**  Only certain status bits may be set or cleared.  
**	   settable                	    not settable
**      ------------------------------  --------------------------
**	allow select into/bulkcopy (4)	don't recover (32)
**	read only (1024)		not recovered (256)
**	dbo use only (2048)		dbname has changed (16384)
**	single user (4096)
**	truncate log on checkpoint (8)
**	no checkpoint on recovery (16)
**	allow null (8192)
**	ddl in tran (512)
**      ALL SETTABLE OPTIONS (15900)
**	abort xact on log full (1, type='D2')
**	no space accounting (2, type='D2')
**	auto identity(4, type='D2')
**	identity in nonunique index(8, type='D2')
*/

/*
** Look for the "settable options" mask in spt_values
*/
select @statopt = number
from master.dbo.spt_values
where type = "D"
  and name = "ALL SETTABLE OPTIONS"

select @stat2opt = number
from master.dbo.spt_values
where type = "D2"
  and name = "ALL SETTABLE OPTIONS"

/*
** If we can't find the option masks, guess at them
*/
if @statopt is null
	select @statopt  = 4 | 8 | 16 | 512 | 1024 | 2048 | 4096 | 8192
if @stat2opt is null
	select @stat2opt = 1 | 2 | 4 | 8

if @dbname is null
begin
	/*
	** 17420, "Settable database options."
	*/
	exec sp_getmessage 17420, @msg output
	print @msg

	if @sptlang = 0
	    select database_options = name
		from master.dbo.spt_values
		where ((type = "D"
			and number & @statopt = number
			and number & @statopt != @statopt)
		    or (type = "D2"
			and number & @stat2opt = number
			and number & @stat2opt != @stat2opt))
		order by name
	else
	    select database_options = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
		where ((type = "D"
			and number & @statopt = number
			and number & @statopt != @statopt)
		    or (type = "D2"
			and number & @stat2opt = number
			and number & @stat2opt != @stat2opt))
		  and msgnum = error
		  and langid = @sptlang
		order by name
	return (0)
end

/*
**  Verify the database name and get the @dbid and @dbuid
*/
select @dbid = dbid, @dbuid = suid
	from master.dbo.sysdatabases
		where name = @dbname

/*
**  If @dbname not found, say so and list the databases.
*/
if @dbid is NULL
begin
	/*
	** 17421, "No such database -- run sp_helpdb to list databases."
	*/
	exec sp_getmessage 17421, @msg output
	print @msg
	return (1)
end

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((suser_id() != @dbuid) and (proc_role("sa_role") != 1))
	return(1)

/*
**  You can not change any of the options in master.  If the user tries to
**  do so tell them they can't.
*/
if @dbid = 1
begin
	/*
	** 17422, "The 'master' database's options can not be changed."
	*/
	exec sp_getmessage 17422, @msg output
	print @msg
	return (1)
end

/*
**  Check remaining parameters.
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
/* 17432, "false" */
exec sp_getmessage 17432, @false out
if @optname is NULL or lower(@optvalue) not in 
	("true", "false", @true, @false) or @optvalue is null
begin
	/*
	** 17423, "Usage: sp_dboption [dbname, optname, {true | false}]"
	*/
	exec sp_getmessage 17423, @msg output
	print @msg
	return (1)
end

/*
**  Use @optname and try to find the right option.
**  If there isn't just one, print appropriate diagnostics and return.
*/
select @optcount = count(*)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
/*
**  If more than one option like @optname, make sure they are not the same
**  option ("trunc" and "trunc.", for example)
*/
if @optcount > 1
begin
	select  @optmsgnum = msgnum
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))

	select @msgcnt = count(msgnum)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
	          and msgnum != @optmsgnum

	/* 
	** msgcnt of 0 indicates we really have just 1 unique dboption, 
	** probably due to alternate spelling.
	*/
	if (@msgcnt = 0) 
		select @optcount = 1
end
/*
** If no option, and alternate language is set, use other language
*/
if @optcount = 0 and @sptlang != 0
begin
    select @optcount = count(*)
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang
    select @whichone = 1
    /*
    **  If more than one option like @optname, make sure they are not the same
    **  option ("trunc" and "trunc.", for example)
    */
    if @optcount > 1
    begin
	select  @optmsgnum = msgnum
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang

	select @msgcnt = count(msgnum)
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang
	          and msgnum != @optmsgnum

	/* 
	** msgcnt of 0 indicates we really have just 1 unique dboption, 
	** probably due to alternate spelling.
	*/
	if (@msgcnt = 0) 
		select @optcount = 1
    end
end

/*
**  If no option, show the user what the options are.
*/
if @optcount = 0
begin
	/*
	** 17424, "Database option doesn't exist or can't be set by user."
	*/
	exec sp_getmessage 17424, @msg output
	print @msg

	/*
	** 17425, "Run sp_dboption with no parameters to see options."
	*/
	exec sp_getmessage 17425, @msg output
	print @msg
	return (0)
end

/*
**  If more than one option like @optname, show the duplicates and return.
*/
if @optcount > 1
begin
	/*
	** 17426, "Database option is not unique."
	*/
	exec sp_getmessage 17426, @msg output
	print @msg

	if @sptlang = 0
	    select duplicate_options = name
		from master.dbo.spt_values
			where name like "%" + @optname + "%"
			  and ((type = "D"
				and number & @statopt = number)
			    or (type = "D2"
				and number & @stat2opt = number))
	else
	    select duplicate_options = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
			where (name like "%" + @optname + "%"
				or description like "%" + @optname + "%")
			  and ((type = "D"
				and number & @statopt = number)
			    or (type = "D2"
				and number & @stat2opt = number))
			  and msgnum = error
			  and langid = @sptlang

	return (1)
end


if db_name() != "master"
begin
	/*
	** 17428, "You must be in the 'master' database in order to change database options."                                
	*/
	exec sp_getmessage 17428, @msg output
	print @msg
	return (1)
end

/*
** User cannot set "tempdb" database in single user mode.
*/
select @statvalue = number
   from master.dbo.spt_values
	where name like "%" + @optname + "%"
	  and ((type = "D"
		and number & @statopt = number)
	    or (type = "D2"
		and number & @stat2opt = number))
 
if (@dbid = 2) and (@statvalue = 4096)
begin
	/*
	** 17436, "The 'single user' option is not valid for the 'tempdb'
	**         database."
	*/
	exec sp_getmessage 17436, @msg output
	print @msg, "sp_dboption"
	return (1)
end

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_dboption"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Get the number which is the bit value to set
*/
if @whichone = 0
    select @statvalue = number, @stattype = type, @success_msg = name
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
else
    select @statvalue = number, @stattype = type, @success_msg = name
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
			and ((type = "D"
			      and number & @statopt = number)
			  or (type = "D2"
			      and number & @stat2opt = number))
			and msgnum = error
			and langid = @sptlang


/*
**  Now update sysdatabases.

*/
if lower(@optvalue) in ("true", @true)
begin
	/*
	**  If this the option to make the database read only,
	**  we need to do some checking first.
	**  Unless it's the master db, no one can be using it.
	**  If it's the master db, only the SA may be using it.
	*/
	if (@statvalue = 1024) and (select count(*)
					from master.dbo.sysprocesses
						where dbid = @dbid) > 0
	begin
		/*
		** 17429, "The database is currently in use -- 'read only' option disallowed."                                       
		*/
		exec sp_getmessage 17429, @msg output
		print @msg
		return (1)
	end

	if (@stattype = "D")
		update master.dbo.sysdatabases
			set status = status | @statvalue
				where dbid = @dbid
	else
		update master.dbo.sysdatabases
			set status2 = status2 | @statvalue
				where dbid = @dbid
	/*
	** 17433, "Database option %1! turned ON for database %2!."
	*/
	exec sp_getmessage 17433, @msg output
	select @name = db_name(@dbid)
	print @msg, @success_msg, @name
end

/*
**  We want to turn it off.
*/
else
begin
	if (@stattype = "D")
		update master.dbo.sysdatabases
			set status = status & ~@statvalue
				where dbid = @dbid
	else
		update master.dbo.sysdatabases
			set status2 = status2 & ~@statvalue
				where dbid = @dbid
	/*
	** 17434, "Database option %1! turned OFF for database %2!."
	*/
	exec sp_getmessage 17434, @msg output
	select @name = db_name(@dbid)
	print @msg, @success_msg, @name
end

/*
**  Advise the user to run the CHECKPOINT command in the database that
**  was changed.
*/
/*
** 17430, "Run the CHECKPOINT command in the database that was changed."
*/
exec sp_getmessage 17430, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dboption', 'anymode'
go
grant execute on sp_dboption to public
go
dump tran master with truncate_only
go
/* %Z%  linux/sproc/%M% %I% %E%  */
/*
**  This file contains the necessary modifications to be made for
**  various DataServer host machines.
**  It sets the DataServer host environment to be Linux.
**  spt_values.low is the number of bytes in a DataServer page.
*/
use master
go

delete spt_values
	where type = "E" and number > 0
go
/* data page size for Linux (Intel X86) */
insert into spt_values (name, number, type, low)
	values ("linux386", 1, "E", @@pagesize)

/* Value to set and clear the high bit for int datatypes for Linux. (Intel X86) */
insert into spt_values (name, number, type, low)
	values ("int high bit", 2, "E", 0x00000080)

/* Value which gives the byte position of the high byte for int datatypes for Linux. (Intel X86) */
insert into spt_values (name, number, type, low)
	values ("int high byte", 3, "E", 4)
go

/*
** Make minimum allowable memory setting equal to value which
** would allow for successful operation of the server on a Linux.
*/
update spt_values
	set low = 3850
		from spt_values
	where number = 104 
		and type = "C"
go

/* command to fix up freeoff on page 24 in all databases */
dbcc dbrepair (master, fixsysindex)

go

dump transaction master to diskdump with truncate_only
go
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_prtsybsysmsgs')
begin
	drop procedure sp_prtsybsysmsgs
end
go
print "Installing sp_prtsybsysmsgs"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/* 
** This procedure is needed to extract messages for the batch that creates
** the sybsystemprocs database. When return parameters are used in an execute
** statement that is a part of a SQL batch, the return values are printed 
** with a heading before subsequent statements in the batch are executed.
** These headings could be confusing to a user that is looking at the results
** of the batch. Hence we print the message in a stored procedure
*/

create procedure sp_prtsybsysmsgs 
@i int, @size int = NULL, @size2 int = NULL
as

declare @msg varchar(250)

exec sp_getmessage @i, @msg out
print @msg, @size, @size2
go
/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for crtsybsystemprocs	18060
** 18060, "The database sybsystemprocs needs to be atleast %1!MB in size. 
** It is currently at %2!MB."
** 18061, "Installing system stored procedures in the sybsystemprocs database."
** 18062, "Database sybsystemprocs of size %1!MB is being created on the 
** default device." 
** 18063, "Done creating database sybsystemprocs on the default device."
** 18064, "Cannot create database sybsystemprocs of size %1!MB on the default 
** device because there is not enough space. Please create this database 
** elsewhere and rerun the installmaster script."
*/

declare @num_pages	int
/*
** The size of sybsystemprocs database has been increased by 4MB
** due to addition of more stored procedures in System 11.0
*/

/* The number of pages in 16 MB. */
select @num_pages = 16777216 / @@pagesize



/* Check if the sybsystemprocs database exists and is of the right size */
if exists (select * from master.dbo.sysdatabases where name="sybsystemprocs")
begin
	declare @size1 int
	declare @size2 int
	select @size1 = sum(size)
	from master.dbo.sysusages where dbid=db_id("sybsystemprocs")
	if (@size1 >= @num_pages)
	begin
		/*
		** 18061, "Installing system stored procedures in the 
		** sybsystemprocs database."
		*/
		exec sp_prtsybsysmsgs 18061
	end
 	else
 	begin

		select @size2 = @size1 / (@num_pages / 16)


		/*
		** 18060, "The database sybsystemprocs needs to be atleast 
		** %1!MB in size. It is currently at %2!MB."
		*/

		exec sp_prtsybsysmsgs 18060, 16, @size2


		return 
 	end
end
else
begin
	/*
	** 18062, "Database sybsystemprocs of size %1!MB is being created on 
	** the default device
	*/	

	exec sp_prtsybsysmsgs 18062, 16
	create database sybsystemprocs on default=16


	/* See if database that got created is of correct size. */
	declare @size int
	select @size = size
	from master.dbo.sysusages where dbid=db_id("sybsystemprocs")
	if (@size = @num_pages)
	begin
		/*
		** 18063, "Done creating database sybsystemprocs on the 
		** default device."
		*/
		exec sp_prtsybsysmsgs 18063

		/*
		** 18061, "Installing system stored procedures in the 
		** sybsystemprocs database."
		*/
		exec sp_prtsybsysmsgs 18061
	end
	else
	begin
		/*
		** 18064, "Cannot create database sybsystemprocs of size 
		** %1!MB on the default device because there is not enough
		** space.  Please create this database elsewhere and rerun the
		** installmaster script."
		*/

		exec sp_prtsybsysmsgs 18064, 16


		drop database sybsystemprocs
		return
	end
end
go

/* Turn on the trunc. log on checkpoint option for the database */
sp_dboption "sybsystemprocs", "trunc", true
go
use sybsystemprocs
go
checkpoint
go
dump transaction sybsystemprocs with truncate_only
go
/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** This file creates the tables needed for the Microsoft stored procedures.
** It also loads the needed values into those tables.
** The tables are:
**	spt_datatype_info_ext
**	spt_datatype_info
**	spt_server_info
**
** Under no circumstances should changes be made to the tables stored in
** this routine unless they are to fix problems with ODBC connectivity.
** These tables interface with the ODBC connectivity routines:
**	sp_columns
**	sp_datatype_info
**
** In addition, any changes made to this file will require the Sybase SQL
** server to be recertified as ODBC compliant by the certification group
** at Sybase (current name is "Interoperability Engineering Technology
** Solutions Group").
*/



/*
** spt_datatype_info_ext
*/

if (exists (select * from sysobjects
		where name = 'spt_datatype_info_ext' and type = 'U'))
    drop table spt_datatype_info_ext
go
create table spt_datatype_info_ext 
(
	user_type	smallint  not null, 
	create_params	varchar(32) null
)
go

grant select on spt_datatype_info_ext to public
go


insert into spt_datatype_info_ext
	/* CHAR 	 user_type, create_params */
	values			 (1, "length" )

insert into spt_datatype_info_ext
	/* VARCHAR	 user_type, create_params */
	values			 (2, "max length" )

insert into spt_datatype_info_ext
	/* BINARY	 user_type, create_params */
	values			 (3, "length" )

insert into spt_datatype_info_ext
	/* VARBINARY	 user_type, create_params */
	values			 (4, "max length" )

insert into spt_datatype_info_ext
	/* NUMERIC	 usertype, create_params */
	values			 (10, "precision,scale" )

insert into spt_datatype_info_ext
	/* SYSNAME	 user_type, create_params */
	values			 (18, "max length" )

insert into spt_datatype_info_ext
	/* DECIMAL	 usertype, create_params */
	values			 (26, "precision,scale" )
go

/* 
** spt_datatype_info
*/
if (exists (select * from sysobjects
		where name = 'spt_datatype_info' and type = 'U'))
    drop table spt_datatype_info
go
create table spt_datatype_info 
(
	ss_dtype	   tinyint	not null, 
	type_name          varchar(32)  not null, 
	data_type          smallint     not null, 
	data_precision     int          null, 
	numeric_scale      smallint     null, 
	numeric_radix      smallint     null, 
	length             int          null, 
	literal_prefix     varchar(32)  null, 
	literal_suffix     varchar(32)  null, 
	create_params      varchar(32)  null, 
	nullable           smallint     not null, 
	case_sensitive     smallint     not null, 
	searchable         smallint     not null, 
	unsigned_attribute smallint     null, 
	money              smallint     not null, 
	auto_increment     smallint     null, 
	local_type_name    varchar(128) not null, 
	aux                int          null
)
go

grant select on spt_datatype_info to public
go

/*
**	There is a complicated set of SQL used to deal with
**	the SQL Server Null data types (MONEYn, INTn, etc.)
**	ISNULL is the only conditional SQL Server function that can be used
**	to differentiate between these types depending on size.
**
**	The aux column in the above table is used to differentiate
**	the null data types from the non-null types.
**
**	The aux column contains NULL for the null data types and 0
**	for the non-null data types.
**
**	The following SQL returns the contents of the aux column (0)
**	for the non-null data types and returns a variable non-zero
**	value for the null data types.
**
**			 " I   I I FFMMDD"
**			 " 1   2 4 484848"
**	isnull(d.aux, ascii(substring("666AAA@@@CB??GG", 
**	2*(d.ss_dtype%35+1)+2-8/c.length, 1))-60)
**
**	The '2*(d.ss_dtype%35+1)+2-8/c.length' selects a specific character of
**	the substring mask depending on the null data type and its size, i.e.
**	null MONEY4 or null MONEY8.  The character selected is then converted
**	to its binary value and an appropriate bias (i.e. 60) is subtracted to
**	return the correct non-zero value.	This value may be used as a
**	constant, i.e. ODBC data type, precision, scale, etc., or used as an
**	index with a substring to pick out a character string, i.e. type name.
**
**	The comments above the substring mask denote which character is
**	selected for each null data type, i.e. In (INTn), Fn (FLOATn), 
**	Mn (MONEYn) and Dn (DATETIMn).
*/


declare @case smallint

select @case = 0
select @case = 1 where 'a' != 'A'

/* Local Binary */
insert into spt_datatype_info values
/* ss_type, name, data_type, prec, scale, rdx, len, prf, suf, 
** cp, nul, case, srch, unsigned, money, auto, local, aux 
*/
(45, "binary", -2, null, null, null, null, "0x", null, 
	"length", 1, 0, 2, null, 0, null, "binary", 0)

/* Local Bit */
insert into spt_datatype_info values
(50, "bit", -7, 1, 0, 2, null, null, null, 
 null, 0, 0, 2, null, 0, null, "bit", 0)

/* Local Char */
insert into spt_datatype_info values
(47, "char", 1, null, null, null, null, "'", "'", 
"length", 1, @case, 3, null, 0, null, "char", 0)

/* Local Datetime */
insert into spt_datatype_info values
(61, "datetime", 11, 23, 3, 10, 16, "'", "'", 
 null, 1, 0, 3, null, 0, null, "datetime", 0)

/* Local Smalldatetime */
insert into spt_datatype_info values
(58, "smalldatetime", 11, 16, 0, 10, 16, "'", "'", 
null, 1, 0, 3, null, 0, null, "smalldatetime", 0)

/* Local Datetimn  sql server type is "datetimn" */
insert into spt_datatype_info values
(111, "smalldatetime", 0, 0, 0, 10, 0, "'", "'", 
null, 1, 0, 3, null, 0, null, "datetime", null)

/* Decimal sql server type is "decimal" */
insert into spt_datatype_info values
(55, "decimal", 3, 38, 0, 10, 0, null, null,
"precision,scale", 1, 0, 2, 0, 0, 0, "decimal", 0)

/* Numeric sql server type is "numeric" */
insert into spt_datatype_info values
(63, "numeric", 2, 38, 0, 10, 0, null, null,
"precision,scale", 1, 0, 2, 0, 0, 0, "numeric", 0)

/* Local Float */
insert into spt_datatype_info values
(62, "float", 6, 15, null, 10, null, null, null, 
null, 1, 0, 2, 0, 0, 0, "float", 0)

/* Local RealFloat   sql server type is "floatn" */
insert into spt_datatype_info values
(109, "float        real", 0, 0, null, 10, 0, null, null, 
null, 1, 0, 2, 0, 0, 0, "real      float", null)

/* Local Real */
insert into spt_datatype_info values
(59, "real", 7, 7, null, 10, null, null, null,
null, 1, 0, 2, 0, 0, 0, "real", 0)

/* Local Smallmoney */
insert into spt_datatype_info values
(122, "smallmoney", 3, 10, 4, 10, null, "$", null, 
null, 1, 0, 2, 0, 1, 0, "smallmoney", 0)

/* Local Int */
insert into spt_datatype_info values
(56, "int", 4, 10, 0, 10, null, null, null, 
null, 1, 0, 2, 0, 0, 0, "int", 0)

/* Local Intn  sql server type is "intn" */
insert into spt_datatype_info values
(38, "smallint     tinyint", 0, 0, 0, 10, 0, null, null, 
null, 1, 0, 2, 0, 0, 0, "tinyint   smallint", null)

/* Local Money */
insert into spt_datatype_info values
(60, "money", 3, 19, 4, 10, null, "$", null, 
null, 1, 0, 2, 0, 1, 0, "money", 0)

/* Local Moneyn  sql server type is "moneyn" */
insert into spt_datatype_info values
(110, "smallmoney", 0, 0, 4, 10, 0, "$", null, 
null, 1, 0, 2, 0, 1, 0, "smallmoneymoney", null)

/* Local Smallint */
insert into spt_datatype_info values
(52, "smallint", 5, 5, 0, 10, null, null, null, 
null, 1, 0, 2, 0, 0, 0, "smallint", 0)

/* Local Text */
insert into spt_datatype_info values
(35, "text", -1, 2147483647, null, null, 2147483647, "'", "'", 
null, 1, @case, 1, null, 0, null, "text", 0)

/* Local Varbinary */
insert into spt_datatype_info values
(37, "varbinary", -3, null, null, null, null, "0x", null, 
"max length", 1, 0, 2, null, 0, null, "varbinary", 0)

/* Local Tinyint */
insert into spt_datatype_info values
(48, "tinyint", -6, 3, 0, 10, null, null, null, 
null, 1, 0, 2, 1, 0, 0, "tinyint", 0)

/* Local Varchar */
insert into spt_datatype_info values
(39, "varchar", 12, null, null, null, null, "'", "'", 
"max length", 1, @case, 3, null, 0, null, "varchar", 0)

/* Local Image */
insert into spt_datatype_info values
(34, "image", -4, 2147483647, null, null, 2147483647, "0x", null, 
null, 1, 0, 1, null, 0, null, "image", 0)
go



dump tran master with truncate_only
go

/*
** spt_server_info
*/
if (exists (select * from sysobjects
		where name = 'spt_server_info' and type = 'U'))
    drop table spt_server_info
go
create table spt_server_info (
	  attribute_id		int, 
	  attribute_name	varchar(60), 
	  attribute_value	varchar(255))
go

insert into spt_server_info
	values (1, "DBMS_NAME", "SQL Server")
insert into spt_server_info
	values (2, "DBMS_VER", @@version)
insert into spt_server_info
	values (6, "DBE_NAME", "")
insert into spt_server_info
	values (10, "OWNER_TERM", "owner")
insert into spt_server_info
	values (11, "TABLE_TERM", "table")
insert into spt_server_info
	values (12, "MAX_OWNER_NAME_LENGTH", "30")
insert into spt_server_info
	values (16, "IDENTIFIER_CASE", "MIXED")
insert into spt_server_info
	values (15, "COLUMN_LENGTH", "30")
insert into spt_server_info
	values (13, "TABLE_LENGTH", "30")
insert into spt_server_info
	values (100, "USERID_LENGTH", "30")
insert into spt_server_info
	values (17, "TX_ISOLATION", "2")
insert into spt_server_info
	values (18, "COLLATION_SEQ", "")
insert into spt_server_info
	values (14, "MAX_QUAL_LENGTH", "30")
insert into spt_server_info
	values (101, "QUALIFIER_TERM", "database")
insert into spt_server_info
	values (19, "SAVEPOINT_SUPPORT", "Y")
insert into spt_server_info
	values (20, "MULTI_RESULT_SETS", "Y")
insert into spt_server_info
	values (102, "NAMED_TRANSACTIONS", "Y")
insert into spt_server_info
	values (103, "SPROC_AS_LANGUAGE", "Y")
insert into spt_server_info
	values (103, "REMOTE_SPROC", "Y")
insert into spt_server_info
	values (22, "ACCESSIBLE_TABLES", "Y")
insert into spt_server_info
	values (104, "ACCESSIBLE_SPROC", "Y")
insert into spt_server_info
	values (105, "MAX_INDEX_COLS", "16")
insert into spt_server_info
	values (106, "RENAME_TABLE", "Y")
insert into spt_server_info
	values (107, "RENAME_COLUMN", "Y")
insert into spt_server_info
	values (108, "DROP_COLUMN", "Y")
insert into spt_server_info
	values (109, "INCREASE_COLUMN_LENGTH", "N")
insert into spt_server_info
	values (110, "DDL_IN_TRANSACTION", "Y")
insert into spt_server_info
	values (111, "DESCENDING_INDEXES", "N")
insert into spt_server_info
	values (112, "SP_RENAME", "Y")
go
/*
** NOTE: the following applies to Microsoft changes, not Sybase.  Do not change
** for Sybase check-ins unless we are synchronizing with Microsoft changes.
**
** The last row in spt_server_info has been used as the version number of the 
** file. The convention is jj.nn.dddd, where:
** 	jj is the major version number ("01" now), 
**	nn is the minor version number ("01" now), and 
**	dddd is the date in the form of month and day (mmdd) of the date you 
**	check in this file.  Add (current year-1991)*12 to the month to keep 
**	in sync with the driver version numbers.  Checking in on Feb 5 1993
**	would mean setting the value to 01.01.2605.
**
*/
insert into spt_server_info
	values (500, "SYS_SPROC_VERSION", "01.01.2822")
go
go
dump transaction sybsystemprocs with truncate_only
go
/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/a_permitboth */
grant select on sysalternates to public
grant select on syscolumns to public
grant select on syscomments to public
grant select on sysdepends to public
grant select on sysindexes to public
grant select on syskeys to public
grant select on sysobjects to public
revoke select on sysobjects(audflags) from public
grant select on sysobjects to sso_role
grant select on sysprocedures to public
grant select on sysprotects to public
grant select on syssegments to public
grant select on systypes to public
grant select on sysusers to public
grant select on syslogs to public
grant select on sysconstraints to public
grant select on sysreferences to public
grant select on sysusermessages to public
grant select on sysattributes to public
go
dump transaction sybsystemprocs with truncate_only
go
/* Temporarily create the #tempmonitors table so it exists
** for the creation of the subordinate sysmon stored procedures.
**
** It will be dropped before sp_sysmon is loaded.
**
**  History:
**	01/25/96 (maxb)  Created for bugid 82625
*/
create table #tempmonitors (
  group_name char(25),
  field_name char(35),
  field_id smallint,
  value int)
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_procxmode')
begin
	drop procedure sp_procxmode
end
go
print "Installing sp_procxmode"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure sp_procxmode
@procname varchar(255) = null,
@tranmode varchar(30) = null
as

declare @uid smallint
declare @oid int
declare @msg varchar(250)	/* message text */

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* If either parameter is null we will be joining with a temporary table
** to convert transaction mode numbers (0, 1, 2) to strings ("Unchained",
** "Chained", "Any Mode").
*/
if ((@procname is null) or (@tranmode is null))
begin
	create table #tranmode (intval integer, charval varchar(15))
	insert into #tranmode values(0, "Unchained")
	insert into #tranmode values(1, "Chained")
	insert into #tranmode values(2, "Any Mode")
end

/* If the first parameter is null, we're to report the transaction-modes
** of every stored procedure in the current database.
*/
if (@procname is null)
begin
	select "procedure name" = o.name, "user name" = user_name(o.uid),
		"transaction mode" = t.charval 
	from sysobjects o, #tranmode t
	where (o.type = "P") and (t.intval = ((o.sysstat2 / 16) & 3))
	order by o.name

	return(0)
end

/* If only the second parameter is null, we're to report the
** transaction-mode of the specified stored procedure.
*/
if ((@procname is not  null) and (@tranmode is null))
begin
	select "procedure name" = o.name, "user name" = user_name(o.uid),
		"transaction mode" = t.charval
	from sysobjects o, #tranmode t
	where (o.type = "P") and (@procname = o.name) and
		(t.intval = ((o.sysstat2 / 16) & 3))

	return(0)
end

/* If neither parameter is null, we're to set the transaction-mode
** of the specified procedure to the specified value.
*/
if ((@procname is not  null) and (@tranmode is not  null))
begin
	/*
	** Update transaction-mode in both sysobjects and DES.
	*/
	dbcc update_tmode(@procname, @tranmode)

	return(0) 
end
go
exec sp_procxmode 'sp_procxmode', 'anymode'
go
grant execute on sp_procxmode to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_validlang')
begin
	drop procedure sp_validlang
end
go
print "Installing sp_validlang"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */
create procedure sp_validlang
@name	varchar(30)
as


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* Check to see if this language is in Syslanguages. */
if exists (select *
		from master.dbo.syslanguages
		where name = @name)
begin
	return 0
end
return 1
go
exec sp_procxmode 'sp_validlang', 'anymode'
go
grant execute on sp_validlang to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_getmessage')
begin
	drop procedure sp_getmessage
end
go
print "Installing sp_getmessage"
go


/* generic/sproc/getmessage	14.2	4/25/91 */

/* Messages from sysmessages
** 17200, "Message number must be greater than or equal to 17000."
** 17201, "'%1!' is not an official language name from Syslanguages."
** 17202, "Message number %1! does not exist in the %2! language."
*/

create procedure sp_getmessage
@message_num int,
@result varchar(255) output,
@language varchar(30) = NULL
as

	declare @lang_id smallint 
	declare @msg varchar(255)
	declare @returncode smallint

	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	/* 
	** Use default language if none specified, 
	** and initialize result 
	*/
	select @lang_id = @@langid, @result = NULL

	/* Only retrieve external errors */
	if @message_num < 17000
	BEGIN
 		/* 17200   "Message number must be greater than or equal to 17000." */
		 select @msg = description from master.dbo.sysmessages
				    where error = 17200
		 print @msg
		 return (1)
	END

	/*
	** Check that language is valid.
	*/
	if @language is not NULL
	BEGIN
	    execute @returncode = sp_validlang @language
	    if @returncode != 0
	    begin
		    /* Us_english is always valid */
		    if @language != "us_english"
		    BEGIN
			    /* 
			    ** 17201, "'%1!' is not an official language
			    **	name from Syslanguages."
			    */
			    select @msg = description from master.dbo.sysmessages
						where error = 17201
						and langid = @@langid

			    /* Get english if the current language is missing */
			    if @msg is null
				select @msg = description from master.dbo.sysmessages
						where error = 17201
						and langid is NULL

			    print @msg, @language
			    return @returncode
		    END

		    /* set to us_english */
		    select @lang_id = NULL
	    end

	    else
	    select @lang_id = langid from master.dbo.syslanguages
			where @language = name

	END

	/* The langid is assigned 0 since it gets its value from @@langid. */
	/* For us_english, we have to insert it as NULL and not 0, this is */
	/* to maintain compatibility with the current conventions          */
	if @lang_id = 0 
	begin 
		select @lang_id = NULL        
	end   

	/* Get message from the proper place */
	/* System messages */
	if @message_num < 20000
	BEGIN
		select @result = description from master.dbo.sysmessages
			   where  langid = @lang_id 
			     and   error = @message_num 

		/* Get english if the current language is missing */
		if @result is null
			select @result = description from master.dbo.sysmessages
                                        where error = @message_num
                                        and (langid is NULL or langid =0)
	END
	else
	/* User messages */
	BEGIN
		/* There is no proper alternate language for user messages */
		select @result = description from sysusermessages
			   where  langid = @lang_id 
			     and   error = @message_num 

		/* this is in here for compatibility with older revs which */
		/* by mistake used to add langid as 0 in sysusermessages   */
		if @result is null and @lang_id is NULL
			select @result = description from sysusermessages
					where (langid is NULL or langid =0)
					and error = @message_num

	END

	/* Warn the user if the message can't be found */
	if @result is null
	begin
		/* 17202, "Message number %1! does not exist in the %2! language." */
		select @msg = description from master.dbo.sysmessages
			where error = 17202
			and langid = @@langid

		if @language is null
			select @language = @@language

		if @msg is null
			select @msg = "Message number %1! does not exist in the %2! language."

		print @msg, @message_num, @language

		return (1)
	end

return (0)
go
exec sp_procxmode 'sp_getmessage', 'anymode'
go
grant execute on sp_getmessage to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_configure')
begin
	drop procedure sp_configure
end
go
print "Installing sp_configure"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/configure */

/*
** Messages for "sp_configure"          17410
**      Must use "langid" when referencing spt_values
**
** 17260, "Can't run %1! from within a transaction." 
** 17410, "Configuration option doesn't exist."
** 17411, "Configuration option is not unique."
** 17413, "The value of the 'number of devices' must be greater than the highest VDEVNO, '%1!', defined in sysdevices."
** 17414, "You can't set the default language to a language ID that is not defined in Syslanguages."
** 17415, "Configuration option value is not legal."
** 17418, "'%1!' is an invalid file command. The valid commands are 'verify', 'read', 'write', and 'restore'."
** 17419, "Configuration option changed. The SQL Server need not be rebooted since the option is dynamic.
** 18123, "Configuration option changed. The SQL Server must be rebooted before the change in effect since the option is static."
** 18124, "No matching configuration options.  Here is a listing of groups:"
** 18125, "Must provide the parameter 'filename'."
** 18133, "The character set, '%1!', is invalid since it is not defined in Syscharsets."
** 18134, "The sortorder, '%1!', is invalid since it is not defined in Syscharsets."
*/

create procedure sp_configure
@configname varchar(80) = NULL,		/* configure option name */
@configvalue int = NULL,		/* configure value */
@configvalue2 varchar(255) = NULL,	/* config file command/charset info */
@configvalue3 varchar(255) = NULL	/* physical name of file */
as

declare @confignum int			/* number of option to be configured */
declare @configcount int		/* number of options like @configname */
declare @whichone	int		/* using english or default lang ? */
declare @cmd		smallint	/* configuration file command */
declare @status int			/* return status for misc calls */
declare @children int			/* number of children in a group */
declare @parent int			/* config number of parent group */
declare @msg varchar(255)		/* temp buffer for messages */
declare @sysconfig smallint		/* contents of sysconfigures.config */
declare @sysname varchar(255)		/* contents of sysconfigures.comment */
declare @sysparent smallint		/* contents of sysconfigures.parent */
declare @sysstatus smallint		/* contents of sysconfigures.status */
declare @value int 			/* default charset/sort order id */
declare @user_displaylevel int		/* user display level */
declare @maxvdevno int			/* highest number of vdevno */
declare @sortorder_id int		/* current sortorder id */
declare @charset_id int			/* current charset id */
declare @sortorder_desc varchar(255)	/* description of the default sort order */
declare @use_wildcard tinyint		/* use wildcard to search option name or not */
declare @match_count int		/* number of option found by name match*/

select @whichone = 0
select @status = 0
select @cmd = 1
select @value = NULL
select @user_displaylevel = NULL
select @sortorder_id =
	value from master.dbo.syscurconfigs where config = 123
select @charset_id =
	value from master.dbo.syscurconfigs where config = 131
select @sortorder_desc =
	description from master.dbo.syscharsets 
	where id = @sortorder_id and csid = @charset_id

select @use_wildcard = 1
/*
**  Disallow running sp_configure within a transaction since it might make
**  recovery impossible.
*/
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_configure"
        return (1)
end
else
begin
        set chained off
end

set transaction isolation level 1

set nocount on

/*
**	If the "default sortorder" is case insensitive dictionary sort order,
** the procedure will just print out all the options and their values 
** without grouping if no option name is given.
*/
if (@sortorder_desc like "%" + "case-insensitive dictionary" + "%"
		and @configname is NULL)
	begin
               select "Parameter Name" = convert(char(30), name),
                        "Default" = convert(char(11), space(11-char_length(
                                    convert(varchar(11), defvalue)))+
                                    convert(varchar(11), defvalue)),
                        "Memory Used" = convert(char(11), space(11-char_length(
                                        convert(varchar(11), b.comment)))+
                                        convert(varchar(11), b.comment)),
                        "Config Value" =convert(char(11), space(11-char_length(
                          isnull(a.value2, convert(char(32), a.value)))) +
                          isnull(a.value2, convert(char(32), a.value))),
                        "Run Value" = convert(char(11), space(11-char_length(
                          isnull(b.value2, convert(char(32), b.value)))) +
                          isnull(b.value2, convert(char(32), b.value)))
                from master.dbo.sysconfigures a,
                        master.dbo.syscurconfigs b
                where
                        a.config *= b.config
                        and parent != 19
                        and a.config != 19
                order by name
		
		return (0)
end


/* Validate the configname if it not NULL */
if @configname is not NULL
begin
	select @configcount = count(*)
    		from master.dbo.sysconfigures
			where name like "%" + @configname + "%"
				and parent != 19

	/*
	**	If configure option is not unique and case-insensitive 
	** dictionary sort order is used, check if unique option found
	** by exact name match, if so, then disable wildcard match 
	** for searching option name.
	*/
	if @configcount > 1 and 
		@sortorder_desc like "%" + "case-insensitive dictionary" + "%"
	begin
		/* check if unique option found by exact name match */
		select @match_count = count(*)
                        from master.dbo.sysconfigures
                                where name = @configname
                                        and parent != 19
		if @match_count =1
		begin
			select @use_wildcard = 0  /* don't use wildcard */
			select @configcount = @match_count
		end
	end

	/*
	** If more than one option like @configname,
	** show the duplicates and return.
	*/
	if @configcount > 1
	begin
		/*
		** 17411, "Configuration option is not unique."
		*/
		exec sp_getmessage 17411, @msg output
		print @msg
		print ""

		select "Parameter Name" = convert(char(30), name),
			"Default" = convert(char(11), space(11-char_length(
				    convert(varchar(11), defvalue)))+
				    convert(varchar(11), defvalue)),
			"Memory Used" = convert(char(11), space(11-char_length(
				   	convert(varchar(11), b.comment)))+
				   	convert(varchar(11), b.comment)),
			"Config Value" =convert(char(11), space(11-char_length(
		 	  isnull(a.value2, convert(char(32), a.value)))) +
			  isnull(a.value2, convert(char(32), a.value))),
			"Run Value" = convert(char(11), space(11-char_length(
			  isnull(b.value2, convert(char(32), b.value)))) +
			  isnull(b.value2, convert(char(32), b.value)))
		from master.dbo.sysconfigures a,
			master.dbo.syscurconfigs b
		where 
			a.config *= b.config
			and name like "%" + @configname + "%"
			and parent != 19
			and a.config != 19
		order by name

		return (1)
	end
	
	/*
	** if it is a valid option and the @configvalue is not NULL,
	** set the option
	*/
	if (@configcount != 0) and (@configvalue is not NULL)
	begin
		/* set @confignum */
		select	@confignum = config,
			@sysstatus = status
			from master.dbo.sysconfigures
				where name like "%" + @configname + "%"
				and parent != 19
				and config != 19

		/*
		** If @configvalue2 is "default",
		** setting the value to default
		*/
		if (@configvalue2 = "default")
			select @value = 1
		else
			select @value = 0

		/*
		**  If the option name is "configuration file"
		*/
		if @confignum = 114
		begin
			/*
			** if the file command is one of the valid
			** commands.
			*/
			if ((@configvalue2 = "read") or
				(@configvalue2 = "write") or
    				(@configvalue2 = "restore") or
    				(@configvalue2 = "verify"))
			begin
				/*
				** if filename is NULL
				*/
				if (@configvalue3 is NULL)
				begin
        				exec sp_getmessage 18125, @msg output
					print @msg
         				return(1)
				end
				/*
				** Must have sa_role to run these
				** commands 
				*/
       				if (proc_role("sa_role") != 1)
				begin
         				return(1)
				end
				else
				begin
					if (@configvalue2 = "verify")
						select @cmd = 2
					else
					if (@configvalue2 = "read")
						select @cmd = 3
					else
					if (@configvalue2 = "write")
						select @cmd = 4
					else
					if (@configvalue2 = "restore")
						select @cmd = 5
				end
			end
			else
			begin
				/*
				** print the message to show the valid
				** file command
				*/
				exec sp_getmessage 17418, @msg output
				print @msg, @configvalue2
				return(1)
			end

			select @status = config_admin(@cmd,0,0,0,NULL,
						@configvalue3)

			if (@status = 1)
			begin
        			return(0)
			end
			else
			begin
				return (1)
			end
		end

		if @confignum = 123
		begin
			/* get current default charset id */
			select @value = value from
				master.dbo.sysconfigures
				where config = 131

			if @configvalue2 is not NULL
			begin
				/* validate the charset id */
				if not exists (select *
					from master..syscharsets
					where name = @configvalue2 
					and type between 1000 and 1999)

				begin
					exec sp_getmessage 18133, @msg output
					print @msg, @configvalue2
					return (1)
				end

				/* get default charset id from name */
				select @value = id
					from master..syscharsets
					where name = @configvalue2 
					and type between 1000 and 1999
			end
		end

		if @confignum = 131
		begin
			/* get current default sortord id */
			select @value = value from
				master.dbo.sysconfigures
				where config = 123

			if @configvalue2 is not NULL
			begin
				/* validate the sortord id */
				if not exists (select *
					from master..syscharsets
					where name = @configvalue2
					and type between 2000 and 2999)
				begin
					exec sp_getmessage 18134, @msg output
					print @msg, @configvalue2
					return (1)
				end

				/* get default sortorder id from name */
				select @value = id
					from master..syscharsets
					where name = @configvalue2
					and type between 2000 and 2999
			end
		end

		/*
		**  If this is the number of devices configuration
		**  parameter, we want to make sure that it's not being
		**  set to lower than the
		**  number of devices in sysdevices.
		*/
		if @confignum = 116
		begin
			/*
			** Get the default value if trying to set the
			** value to the default value
			*/
			if (@value = 1)
			begin
				select @configvalue = convert(int, defvalue)
					from master.dbo.syscurconfigs
					where config = 116
			end

			/*
			**  Get the max vdevno.
			*/
			select @maxvdevno = max(
				convert(tinyint,
					substring(convert(binary(4), d.low),
					v.low, 1)))
				from master.dbo.sysdevices d,
				master.dbo.spt_values v

			if (@configvalue <= @maxvdevno)
			begin
				exec sp_getmessage 17413, @msg output
				print @msg, @maxvdevno
				return (1)
			end
		end


		/* 
		**  If this is the number of default language, we want
		**  to make sure that the new value is a valid language
		**  id in Syslanguages.
		*/ 
		if @confignum = 124
		begin
			if not exists (select *
				from master.dbo.syslanguages
					where langid = @configvalue)   
			begin
				/* 0 is default language, us_english */
				if @configvalue != 0
				begin
					exec sp_getmessage 17414, @msg output
					print @msg
					return (1)
				end
			end
		end

		/* call config_admin() to set the new value */
		select @status = config_admin(@cmd, @confignum,
					 @configvalue, @value, NULL, NULL)

		/* if successful */
		if (@status = 1)
		begin
			/* Display the new value */
			select "Parameter Name" = convert(char(30), name),
			  "Default" = convert(char(11), space(11-char_length(
				convert(varchar(11), defvalue))) +
			  	convert(varchar(11), defvalue)),
			  "Memory Used" = convert(char(11),space(11-char_length(
			  	convert(varchar(11), c.comment))) +
			  	convert(varchar(11), c.comment)),
			  "Config Value" = convert(char(11),
				space(11-char_length(
		 	  	isnull(b.value2, convert(char(32), b.value)))) +
		 	  	isnull(b.value2, convert(char(32), b.value))),
			  "Run Value"  = convert(char(11), space(11-char_length(
			  	isnull(c.value2, convert(char(32), c.value)))) +
			  	isnull(c.value2, convert(char(32), c.value)))
			from master.dbo.sysconfigures b,
				master.dbo.syscurconfigs c
			where 
				b.config = @confignum and
				b.config *= c.config

			/*
			** print reboot message if this option is not
			** dynamic.
			*/
			select @sysstatus = @sysstatus & 8
			if @sysstatus = 8
			begin
				exec sp_getmessage 17419, @msg output
				print @msg
			end
			else
			begin
				exec sp_getmessage 18123, @msg output
				print @msg
			end

			return(0)
		end
		else
			return(1)
	end
end

/*
** @configcount=0 implies @configname is not valid
** @configname=NULL implies displaying all the parameters except for
** the parameters with the config number equal to 19 or the parent equal
** to 19 since those parameters are displayed by sp_cacheconfig.
*/
if (@configcount =0)
begin
	exec sp_getmessage 18124, @msg output
	print @msg
	select convert(char(50), name)
		from master.dbo.sysconfigures
		where config < 100
		and parent != 19
		and config != 19
		order by name
	return(1)
end
else if (@configname is NULL)
	select @configname = "Config"

/*
** retrieve the display level from sysattributes
*/
select @user_displaylevel = int_value from master.dbo.sysattributes where
	class = 4 AND
	attribute = 0 AND
	object_type = 'L' AND
	object = suser_id()

/*
** set the default display level to 10 if it is not defined in sysattributes
*/
if (@user_displaylevel = NULL)
	select @user_displaylevel = 10

/*
** 	If @use_wildcard = 0 and the default sortorder is case-insensitive 
** dictionary sort order, use exact match: name = @configname to get row, 
** otherwise use wildcard match: name like "%" + @configname + "%".
*/

if (@use_wildcard = 0 and @sortorder_desc like "%" + "case-insensitive dictionary" + "%")
	select  @confignum = config,
		@parent = config,
		@sysname = name,
        	@sysstatus = status
	from master.dbo.sysconfigures
		where name = @configname
		and config != 19
else
	select	@confignum = config, 
		@parent = config,
		@sysname = name,
		@sysstatus = status
	from master.dbo.sysconfigures
		where name like "%" + @configname + "%"
		and config != 19

select	@children = count(*)
	from master.dbo.sysconfigures
	where parent =  @confignum

if @children = 0
begin
	/* @@nestlevel is problem area if a sproc calls sp_configure */
	/* could pass in another param when recursing */
	if @@nestlevel > 1
	begin
		/* reached a leaf, notify parent */
		return(1)
	end
	else
	begin
		/* display the information of the config parameter */
		select "Parameter Name" = convert(char(30), name),
			"Default" = convert(char(11), space(11-char_length(
			  convert(varchar(11), defvalue))) +
			  convert(varchar(11), defvalue)),
			"Memory Used" = convert(char(11), space(11-char_length(
			  convert(varchar(11), c.comment))) +
			  convert(varchar(11), c.comment)),
			"Config Value" = convert(char(11), space(11-char_length(
		 	  isnull(b.value2, convert(char(32), b.value)))) +
		 	  isnull(b.value2, convert(char(32), b.value))),
			"Run Value"  = convert(char(11), space(11-char_length(
			  isnull(c.value2, convert(char(32), c.value)))) +
			  isnull(c.value2, convert(char(32), c.value)))
		from master.dbo.sysconfigures b,
			master.dbo.syscurconfigs c
		where 
			b.config *= c.config
			and name like "%" + @configname + "%"
			and b.config != 19
	end
end
else
begin
	select @msg = "Group: " + @sysname
	print ""
	print @msg
	print ""

	/* this poor guy has kids, so recurse to leaves */
	declare config_curs cursor for 
		select config, name, parent 
		from master.dbo.sysconfigures 
		where parent = @parent
		order by name

	open config_curs

	fetch config_curs into @sysconfig, @sysname, @sysparent

	while (@@sqlstatus = 0)
	begin

		execute @status = sp_configure @sysname


		if (@status = 1)
		begin
			/*
			** this guy has leaves as kids,
			** so print out the leaves with
			** display level <= @user_displaylevel
			** Note: If a config parameter has more than one
			** parent, the extra parents are stored in
			** 'sysattribures'.
			*/
			create table #configure_temp (config int)

			insert into #configure_temp
				select a.config
					from master.dbo.sysconfigures a,
					master.dbo.syscurconfigs b
					where
			  	   	   display_level <= @user_displaylevel
				   	   and parent = @parent
					   and a.config != 19
					   and a.config = b.config
		  		    union
				    select config
					from master.dbo.syscurconfigs,
					master.dbo.sysattributes
					where
			  	   	   display_level <= @user_displaylevel
					   and class = 4
					   and attribute = 1
					   and object_type = 'CP'
				   	   and int_value = @parent
					   and object = config
					   and config != 19

			if exists (select * from #configure_temp)
			begin
			 select "Parameter Name" = convert(char(30), name),
			 "Default" = convert(char(11), space(11-char_length(
				convert(varchar(11), defvalue))) +
				convert(varchar(11), defvalue)),
			 "Memory Used" = convert(char(11), space(11-char_length(
				convert(varchar(11), c.comment))) +
				convert(varchar(11), c.comment)),
			 "Config Value" = convert(char(11),space(11-char_length(
		 	 	isnull(b.value2, convert(char(32), b.value)))) +
		 	 	isnull(b.value2, convert(char(32), b.value))),
			 "Run Value"  = convert(char(11), space(11-char_length(
			 	isnull(c.value2, convert(char(32), c.value)))) +
			 	isnull(c.value2, convert(char(32), c.value)))
			 from master.dbo.sysconfigures b,
				master.dbo.syscurconfigs c
			 where b.config in
				(select config from #configure_temp)
				and b.config = c.config
			 order by name
			end

			drop table #configure_temp

			close config_curs
			deallocate cursor config_curs

			return(0)
		end
		else
		begin
			/*
			** this lucky guy has grandkids, so, continue
			*/
			fetch config_curs into 
				@sysconfig, @sysname, @sysparent

		end
	end

	close config_curs
	deallocate cursor config_curs

	return(0)
end

go


go
exec sp_procxmode 'sp_configure', 'anymode'
go
grant execute on sp_configure to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dboption')
begin
	drop procedure sp_dboption
end
go
print "Installing sp_dboption"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/a_values */

/*
** Messages for "sp_dboption"           17420
**      Use "langid" when looking at spt_values ???
**
** 17260, "Can't run %1! from within a transaction." 
** 17420, "Settable database options."
** 17421, "No such database -- run sp_helpdb to list databases."
** 17422, "The 'master' database's options can not be changed."
** 17423, "Usage: sp_dboption [dbname, optname, {true | false}]"
** 17424, "Database option doesn't exist or can't be set by user."
** 17425, "Run sp_dboption with no parameters to see options."
** 17426, "Database option is not unique."
** 17428, "You must be in the 'master' database in order to change
**	database options."                                
** 17429, "The database is currently in use -- 'read only' option
**	disallowed."                                       
** 17430, "Run the CHECKPOINT command in the database that was changed."
** 17431, "true"
** 17432, "false"
** 17433, "Database option '%1!' turned ON for database '%2!'."
** 17434, "Database option '%1!' turned OFF for database '%2!'."
** 17289, "Set your curwrite to the hurdle of current database."
** 17436, "The 'single user' option is not valid for the 'tempdb'
**	database."
*/

create procedure sp_dboption
@dbname varchar(30) = NULL,		/* database name to change */
@optname varchar(20) = NULL,		/* option name to turn on/off */
@optvalue varchar(10) = NULL		/* true or false */
as

declare @dbid int			/* dbid of the database */
declare @dbuid int			/* id of the owner of the database */
declare @statvalue smallint,		/* number of option */
	@stattype char(2),		/* status field flag */
	@statopt smallint,		/* option mask, part 1 */
	@stat2opt smallint		/* option mask, part 2 */
declare @optcount int			/* number of options like @optname */
declare @success_msg varchar(255)	/* success status message */
declare @msg varchar(250)
declare @sptlang	int
declare @true		varchar(10)
declare @false		varchar(10)
declare @whichone	int		/* which language? */
declare @name		varchar(30)
declare	@optmsgnum	int		/* identify one msgnum to compare */
declare	@msgcnt		int		/* count distinct dups */



if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @sptlang = @@langid,  @whichone = 0

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17050 and 17069
		and langid = @@langid)
	select @sptlang = 0
end


/*
**  If no @dbname given, just list the possible dboptions.
**  Only certain status bits may be set or cleared.  
**	   settable                	    not settable
**      ------------------------------  --------------------------
**	allow select into/bulkcopy (4)	don't recover (32)
**	read only (1024)		not recovered (256)
**	dbo use only (2048)		dbname has changed (16384)
**	single user (4096)
**	truncate log on checkpoint (8)
**	no checkpoint on recovery (16)
**	allow null (8192)
**	ddl in tran (512)
**      ALL SETTABLE OPTIONS (15900)
**	abort xact on log full (1, type='D2')
**	no space accounting (2, type='D2')
**	auto identity(4, type='D2')
**	identity in nonunique index(8, type='D2')
*/

/*
** Look for the "settable options" mask in spt_values
*/
select @statopt = number
from master.dbo.spt_values
where type = "D"
  and name = "ALL SETTABLE OPTIONS"

select @stat2opt = number
from master.dbo.spt_values
where type = "D2"
  and name = "ALL SETTABLE OPTIONS"

/*
** If we can't find the option masks, guess at them
*/
if @statopt is null
	select @statopt  = 4 | 8 | 16 | 512 | 1024 | 2048 | 4096 | 8192
if @stat2opt is null
	select @stat2opt = 1 | 2 | 4 | 8

if @dbname is null
begin
	/*
	** 17420, "Settable database options."
	*/
	exec sp_getmessage 17420, @msg output
	print @msg

	if @sptlang = 0
	    select database_options = name
		from master.dbo.spt_values
		where ((type = "D"
			and number & @statopt = number
			and number & @statopt != @statopt)
		    or (type = "D2"
			and number & @stat2opt = number
			and number & @stat2opt != @stat2opt))
		order by name
	else
	    select database_options = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
		where ((type = "D"
			and number & @statopt = number
			and number & @statopt != @statopt)
		    or (type = "D2"
			and number & @stat2opt = number
			and number & @stat2opt != @stat2opt))
		  and msgnum = error
		  and langid = @sptlang
		order by name
	return (0)
end

/*
**  Verify the database name and get the @dbid and @dbuid
*/
select @dbid = dbid, @dbuid = suid
	from master.dbo.sysdatabases
		where name = @dbname

/*
**  If @dbname not found, say so and list the databases.
*/
if @dbid is NULL
begin
	/*
	** 17421, "No such database -- run sp_helpdb to list databases."
	*/
	exec sp_getmessage 17421, @msg output
	print @msg
	return (1)
end

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((suser_id() != @dbuid) and (proc_role("sa_role") != 1))
	return(1)

/*
**  You can not change any of the options in master.  If the user tries to
**  do so tell them they can't.
*/
if @dbid = 1
begin
	/*
	** 17422, "The 'master' database's options can not be changed."
	*/
	exec sp_getmessage 17422, @msg output
	print @msg
	return (1)
end

/*
**  Check remaining parameters.
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
/* 17432, "false" */
exec sp_getmessage 17432, @false out
if @optname is NULL or lower(@optvalue) not in 
	("true", "false", @true, @false) or @optvalue is null
begin
	/*
	** 17423, "Usage: sp_dboption [dbname, optname, {true | false}]"
	*/
	exec sp_getmessage 17423, @msg output
	print @msg
	return (1)
end

/*
**  Use @optname and try to find the right option.
**  If there isn't just one, print appropriate diagnostics and return.
*/
select @optcount = count(*)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
/*
**  If more than one option like @optname, make sure they are not the same
**  option ("trunc" and "trunc.", for example)
*/
if @optcount > 1
begin
	select  @optmsgnum = msgnum
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))

	select @msgcnt = count(msgnum)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
	          and msgnum != @optmsgnum

	/* 
	** msgcnt of 0 indicates we really have just 1 unique dboption, 
	** probably due to alternate spelling.
	*/
	if (@msgcnt = 0) 
		select @optcount = 1
end
/*
** If no option, and alternate language is set, use other language
*/
if @optcount = 0 and @sptlang != 0
begin
    select @optcount = count(*)
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang
    select @whichone = 1
    /*
    **  If more than one option like @optname, make sure they are not the same
    **  option ("trunc" and "trunc.", for example)
    */
    if @optcount > 1
    begin
	select  @optmsgnum = msgnum
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang

	select @msgcnt = count(msgnum)
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang
	          and msgnum != @optmsgnum

	/* 
	** msgcnt of 0 indicates we really have just 1 unique dboption, 
	** probably due to alternate spelling.
	*/
	if (@msgcnt = 0) 
		select @optcount = 1
    end
end

/*
**  If no option, show the user what the options are.
*/
if @optcount = 0
begin
	/*
	** 17424, "Database option doesn't exist or can't be set by user."
	*/
	exec sp_getmessage 17424, @msg output
	print @msg

	/*
	** 17425, "Run sp_dboption with no parameters to see options."
	*/
	exec sp_getmessage 17425, @msg output
	print @msg
	return (0)
end

/*
**  If more than one option like @optname, show the duplicates and return.
*/
if @optcount > 1
begin
	/*
	** 17426, "Database option is not unique."
	*/
	exec sp_getmessage 17426, @msg output
	print @msg

	if @sptlang = 0
	    select duplicate_options = name
		from master.dbo.spt_values
			where name like "%" + @optname + "%"
			  and ((type = "D"
				and number & @statopt = number)
			    or (type = "D2"
				and number & @stat2opt = number))
	else
	    select duplicate_options = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
			where (name like "%" + @optname + "%"
				or description like "%" + @optname + "%")
			  and ((type = "D"
				and number & @statopt = number)
			    or (type = "D2"
				and number & @stat2opt = number))
			  and msgnum = error
			  and langid = @sptlang

	return (1)
end


if db_name() != "master"
begin
	/*
	** 17428, "You must be in the 'master' database in order to change database options."                                
	*/
	exec sp_getmessage 17428, @msg output
	print @msg
	return (1)
end

/*
** User cannot set "tempdb" database in single user mode.
*/
select @statvalue = number
   from master.dbo.spt_values
	where name like "%" + @optname + "%"
	  and ((type = "D"
		and number & @statopt = number)
	    or (type = "D2"
		and number & @stat2opt = number))
 
if (@dbid = 2) and (@statvalue = 4096)
begin
	/*
	** 17436, "The 'single user' option is not valid for the 'tempdb'
	**         database."
	*/
	exec sp_getmessage 17436, @msg output
	print @msg, "sp_dboption"
	return (1)
end

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_dboption"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Get the number which is the bit value to set
*/
if @whichone = 0
    select @statvalue = number, @stattype = type, @success_msg = name
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
else
    select @statvalue = number, @stattype = type, @success_msg = name
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
			and ((type = "D"
			      and number & @statopt = number)
			  or (type = "D2"
			      and number & @stat2opt = number))
			and msgnum = error
			and langid = @sptlang


/*
**  Now update sysdatabases.

*/
if lower(@optvalue) in ("true", @true)
begin
	/*
	**  If this the option to make the database read only,
	**  we need to do some checking first.
	**  Unless it's the master db, no one can be using it.
	**  If it's the master db, only the SA may be using it.
	*/
	if (@statvalue = 1024) and (select count(*)
					from master.dbo.sysprocesses
						where dbid = @dbid) > 0
	begin
		/*
		** 17429, "The database is currently in use -- 'read only' option disallowed."                                       
		*/
		exec sp_getmessage 17429, @msg output
		print @msg
		return (1)
	end

	if (@stattype = "D")
		update master.dbo.sysdatabases
			set status = status | @statvalue
				where dbid = @dbid
	else
		update master.dbo.sysdatabases
			set status2 = status2 | @statvalue
				where dbid = @dbid
	/*
	** 17433, "Database option %1! turned ON for database %2!."
	*/
	exec sp_getmessage 17433, @msg output
	select @name = db_name(@dbid)
	print @msg, @success_msg, @name
end

/*
**  We want to turn it off.
*/
else
begin
	if (@stattype = "D")
		update master.dbo.sysdatabases
			set status = status & ~@statvalue
				where dbid = @dbid
	else
		update master.dbo.sysdatabases
			set status2 = status2 & ~@statvalue
				where dbid = @dbid
	/*
	** 17434, "Database option %1! turned OFF for database %2!."
	*/
	exec sp_getmessage 17434, @msg output
	select @name = db_name(@dbid)
	print @msg, @success_msg, @name
end

/*
**  Advise the user to run the CHECKPOINT command in the database that
**  was changed.
*/
/*
** 17430, "Run the CHECKPOINT command in the database that was changed."
*/
exec sp_getmessage 17430, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dboption', 'anymode'
go
grant execute on sp_dboption to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_validaltlang')
begin
	drop procedure sp_validaltlang
end
go
print "Installing sp_validaltlang"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */

create procedure sp_validaltlang
@name	varchar(30)
as


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* Check to see if this alias is in Syslanguages. */
if exists (select *
		from master.dbo.syslanguages
		where alias = @name)
begin
	return 0
end
return 1
go
exec sp_procxmode 'sp_validaltlang', 'anymode'
go
grant execute on sp_validaltlang to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_namecrack')
begin
	drop procedure sp_namecrack
end
go
print "Installing sp_namecrack"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/lock */

create procedure sp_namecrack
@name	varchar(123),
@site	varchar(30) = null output,
@db	varchar(30) = null output,
@owner	varchar(30) = null output,
@object	varchar(30) = null output
as


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @site = null, @db = null, @owner = null, @object = null

/*
**  Is there a site name?
*/
if @name like "%.%.%.%"
begin
	select @site = substring(@name, 1, charindex(".", @name) - 1)
	select @name = substring(@name, charindex(".", @name) + 1, 125)
end

/*
**  Is there a database name?
*/
if @name like "%.%.%"
begin
	select @db = substring(@name, 1, charindex(".", @name) - 1)
	select @name = substring(@name, charindex(".", @name) + 1, 125)
end

/*
**  Is there a owner?
*/
if @name like "%.%"
begin
	select @owner = substring(@name, 1, charindex(".", @name) - 1)
	select @name = substring(@name, charindex(".", @name) + 1, 125)
end

select @object = @name

return (0)
go
exec sp_procxmode 'sp_namecrack', 'anymode'
go
grant execute on sp_namecrack to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_chklangparam')
begin
	drop procedure sp_chklangparam
end
go
print "Installing sp_chklangparam"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/chklangparam */
/*
** sp_checklangparam is called by sp_addlanguage to check the lists of
** full month names, short month names, and day names.  It returns a status
** indicating whether any errors were found:
**	0 - name list is valid
**	1 - spaces were found, which are not allowed
**	2 - not enough names in the list (must be exactly @numnames of them)
**	3 - too many names in the list (must be exactly @numnames of them)
**	4 - some name(s) are too long
**	5 - some name(s) have non-aphabetic characters
*/

/*
** Messages for "sp_chklangparam"       17373
**
** %1! is either "month" or "day" 
** 17373, "List of %1! names contains spaces, which are not allowed."
** 17374, "List of %1! names has too few names."
** 17375, "List of %1! names has too many names."
** 17376, "List of %1! names has name(s) which are too long."
** 17377, "List of %1! names contains name(s) which have '%2!' non-alphabetic characters."
** %2! is the character set name 
*/

create procedure sp_chklangparam
@namelist varchar(251),		/* month or day name list */
@msgparam varchar(30),		/* name of list, for error messages */
@numnames int,			/* correct number of names in the list */
@maxnamelen int			/* maximum length of any name in list */
as

	declare @totallen		int
	declare @mthlen			int
	declare @mthname		varchar(251)
	declare @msg			varchar(255)
        declare @csid                   tinyint
        declare @csname                 varchar(30)

	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

        /* Get the Character Set id (csid) */
	/* (Up to the version 4.2)
	   select @csid = csid from master..syscharsets
                where id = (select value from master..sysconfigures
                        where config = 123)
	*/
	/* (After 4.9) */
	select @csid = value from master..sysconfigures 
			where config = 131

        /* Get the Character Set Name (csname) */
        select @csname = name from master..syscharsets
                where id = @csid and type < 2000

	/* Make sure the list has no blanks. */
	if ( charindex( " ", @namelist ) != 0 )
	begin
		/*
		** 17373, "List of %1! names contains spaces, which are not allowed."
		*/
		exec sp_getmessage 17373, @msg output
		print @msg, @msgparam
		return 1
	end

	/* Keep track of number of *CHARACTERS* */
	select @totallen = char_length( @namelist )
	/* select @totallen = datalength( @namelist ) */
	while ( @totallen > 0 )
	begin
		/* Move to the next name in the list. */
		select @namelist = right( @namelist, @totallen )

		/* If this is not the last name in the list then there must
		** be another comma.
		*/
		if ( @numnames > 1 )
		begin
			select @mthlen = charindex( ",", @namelist ) - 1
			if ( @mthlen < 0 )
			begin
				/*
				** 17374, "List of %1! names has too few names."
				*/
				exec sp_getmessage 17374, @msg output
				print @msg, @msgparam
				return 2
			end
		end

		/* This is the last name in the list, so there cannot be
		** another comma.  This name is all remaining characters
		** in the list.
		*/
		else
		begin
			if ( charindex( ",", @namelist ) != 0 )
			begin
				/*
				** 17375, "List of %1! names has too many names."
				*/
				exec sp_getmessage 17375, @msg output
				print @msg, @msgparam
				return 3
			end
			select @mthlen = @totallen
		end

		/* Check the name length. */
		if ( @mthlen > @maxnamelen )
		begin
			/*
			** 17376, "List of %1! names has name(s) which are too long."
			*/
			exec sp_getmessage 17376, @msg output
			print @msg, @msgparam
			return 4
		end

		/*
		** Check to see that the names contain only valid
		** P_ALPHA characters; not even DIGITs should be allowed.
		** Note that valid_name() returns a bit-mask of the lexical
		** values found in the string passed to it, where P_ALPHA
		** is 0x01.
		*/
		if (valid_name(substring(@namelist, 1, @mthlen)) != 1)
		begin
      			/*
			** 17377, "List of %1! names contains name(s) which have 
			** '%2!' non-alphabetic characters."
			*/
			exec sp_getmessage 17377, @msg output
			print @msg, @msgparam, @csname
			return 5
		end

		/* Move to the next name in the list. */
		select @numnames = @numnames - 1
		select @totallen = @totallen - @mthlen - 1
	end

	/* No problems were found with the name list. */
	return 0
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpgroup')
begin
	drop procedure sp_helpgroup
end
go
print "Installing sp_helpgroup"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helpgroup"          17630
**
** 17333, "No group with the specified name exists."
*/
create procedure sp_helpgroup
@grpname varchar(30) = NULL		/* group name of interest */
as

declare @msg varchar(90)
declare @len1 int, @len2 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  If no group name given, list all the groups.
**  User ids range from -16383 to +16383 and group ids are > 16383 or = 0.
*/
if @grpname is NULL
begin
	select Group_name = name, Group_id = gid
		from sysusers
			where (uid > 16383 or uid = 0)
		order by name

	return (0)
end

/*
**  Check to see if group exists.
*/
if not exists (select *
			from sysusers
		where name = @grpname
			and (uid > 16383 or uid = 0))
	or exists (select name from master.dbo.syssrvroles         
		where name = @grpname) 
begin
	/* 17333, "No group with the specified name exists." */
	exec sp_getmessage 17333, @msg out
	print @msg
	return (1)
end

if (@grpname != "public")
begin
	/*
	**  List the particulars for the group.
	*/
	select @len1 = max(datalength(g.name)),
	       @len2 = max(datalength(u.name))
			from sysusers u, sysusers g
				where g.name like @grpname
				and g.uid = u.gid
				and (g.uid > 16383 or g.uid = 0)
				and u.uid != u.gid

	if (@len1 > 25 or @len2 > 25)
    	    select Group_name = g.name, Group_id = g.gid,
		Users_in_group = u.name, Userid = u.uid
			from sysusers u, sysusers g
				where g.name like @grpname
				and g.uid = u.gid
				and (g.uid > 16383 or g.uid = 0)
				and u.uid != u.gid
			order by g.name, u.name
	else
    	    select Group_name = convert(char(25), g.name), Group_id = g.gid,
		Users_in_group = convert(char(25), u.name), Userid = u.uid
			from sysusers u, sysusers g
				where g.name like @grpname
				and g.uid = u.gid
				and (g.uid > 16383 or g.uid = 0)
				and u.uid != u.gid
			order by g.name, u.name
end
else
begin
	/*
	**  Special case for "public" group.  List all users, including users
	**  in other groups.  They also belong to "public" group.
	*/
	select @len1 = max(datalength(g.name)),
	       @len2 = max(datalength(u.name))
			from sysusers u, sysusers g
				where g.name like @grpname
				and (g.uid > 16383 or g.uid = 0)
				and u.uid != u.gid

	if (@len1 > 25 or @len2 > 25)
    	    select Group_name = g.name, Group_id = g.gid,
		Users_in_group = u.name, Userid = u.uid
			from sysusers u, sysusers g
				where g.name like @grpname
				and (g.uid > 16383 or g.uid = 0)
				and u.uid != u.gid
			order by g.name, u.name
	else
    	    select Group_name = convert(char(25), g.name), Group_id = g.gid,
		Users_in_group = convert(char(25), u.name), Userid = u.uid
			from sysusers u, sysusers g
				where g.name like @grpname
				and (g.uid > 16383 or g.uid = 0)
				and u.uid != u.gid
			order by g.name, u.name
end
return (0)
go
exec sp_procxmode 'sp_helpgroup', 'anymode'
go
grant execute on sp_helpgroup to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpuser')
begin
	drop procedure sp_helpuser
end
go
print "Installing sp_helpuser"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helpuser"           17700
**
** 17700, "Users aliased to user."
** 17701, "The name supplied is a group name."
** 17702, "The name supplied is aliased to another user."
** 17703, "The name supplied is not a user, group, or aliased."
*/
create procedure sp_helpuser
@name_in_db varchar(30) = NULL
as

declare @msg varchar(100)
declare @len1 int, @len2 int, @len3 int, @len4 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

/*
**  If no @name_in_db, list all the users.
**  User ids range from -16383 to +16383 and group ids are > 16383.
*/
if @name_in_db is NULL
begin

    select @len1 = max(datalength(u.name)),
	@len2 = max(datalength(g.name)),
	@len3 = max(datalength(m.name)),
	@len4 = max(datalength(m.dbname))
		from sysusers u, sysusers g,
			master.dbo.syslogins m
		where u.suid *= m.suid
			and u.gid *= g.uid
			and u.uid <= 16383 and u.uid != 0

    if (@len1 > 17 or @len2 > 17 or @len3 > 17 or @len4 > 15)


	select Users_name = u.name, ID_in_db = u.uid,
		Group_name = g.name,
		Login_name = m.name,
		Default_db = m.dbname
			from sysusers u, sysusers g,
				master.dbo.syslogins m
			where u.suid *= m.suid
				and u.gid *= g.uid
				and u.uid <= 16383 and u.uid != 0
			order by Users_name

   else


	select Users_name = convert(char(17), u.name), ID_in_db = u.uid,
		Group_name = convert(char(17), g.name),
		Login_name = convert(char(17), m.name),
		Default_db = convert(char(15), m.dbname)
			from sysusers u, sysusers g,
				master.dbo.syslogins m
			where u.suid *= m.suid
				and u.gid *= g.uid
				and u.uid <= 16383 and u.uid != 0
			order by Users_name


    return (0)
end

/*
**  See if the @name_in_db is a user.  If so, print out the info for
**  the user, including users pretending to be the user (sysaliases).
*/
if exists (select *
		from sysusers
			where name = @name_in_db
				and uid <= 16383 and uid != 0)
begin

	select @len1 = max(datalength(u.name)),
	    @len2 = max(datalength(g.name)),
	    @len3 = max(datalength(m.name)),
	    @len4 = max(datalength(m.dbname))
		from sysusers u, sysusers g,
			master.dbo.syslogins m
		where u.suid *= m.suid
			and u.gid *= g.uid
			and u.name = @name_in_db
			and u.uid <= 16383 and u.uid != 0

	if (@len1 > 17 or @len2 > 17 or @len3 > 17 or @len4 > 15)


	    select Users_name = u.name, ID_in_db = u.uid,
		Group_name = g.name,
		Login_name = m.name,
		Default_db = m.dbname
			from sysusers u, sysusers g,
				master.dbo.syslogins m
			where u.suid *= m.suid
				and u.gid *= g.uid
				and u.name = @name_in_db
				and u.uid <= 16383 and u.uid != 0

	else


	    select Users_name = convert(char(17), u.name), ID_in_db = u.uid,
		Group_name = convert(char(17), g.name),
		Login_name = convert(char(17), m.name),
		Default_db = convert(char(15), m.dbname)
			from sysusers u, sysusers g,
				master.dbo.syslogins m
			where u.suid *= m.suid
				and u.gid *= g.uid
				and u.name = @name_in_db
				and u.uid <= 16383 and u.uid != 0    


	declare @suid	smallint

	select @suid = suid
		from sysusers 
			where name = @name_in_db

	/*
	** If anyone is using @name_in_db as an alias print it out.
	*/
	if exists (select *
			from sysalternates
		where altsuid = @suid)
	begin
		/* 17700, "Users aliased to user." */
		exec sp_getmessage 17700, @msg out
		print @msg
		select Login_name = suser_name(suid)
			from sysalternates
				where altsuid = @suid
			order by Login_name
	end

	return (0)
end

/*
**  Maybe the @name_in_db is a group.  Is so print out the info.
*/
if exists (select *
		from sysusers
			where name = @name_in_db
				and (uid > 16383 or uid = 0))
begin
	/* 17701, "The name supplied is a group name." */
	exec sp_getmessage 17701, @msg out
	print @msg
	execute sp_helpgroup @name_in_db
	return (0)
end

/*
**  Last thing to try is that the @name_in_db might be aliased.
*/
if exists (select *
		from sysalternates
			where suid = suser_id(@name_in_db))
begin
	/* 17702, "The name supplied is aliased to another user." */
	exec sp_getmessage 17702, @msg out
	print @msg


	select @len1 = max(datalength(u.name)),
	    @len2 = max(datalength(g.name)),
	    @len3 = max(datalength(m.name)),
	    @len4 = max(datalength(m.dbname))
		from sysusers u, sysusers g, sysalternates a,
			master.dbo.syslogins m
		where u.suid *= m.suid
			and u.gid *= g.uid
			and u.uid <= 16383 and u.uid != 0
			and a.suid = suser_id(@name_in_db)
			and a.altsuid = u.suid

	if (@len1 > 17 or @len2 > 17 or @len3 > 17 or @len4 > 15)


	    select Alias_name = u.name, ID_in_db = u.uid,
		Group_name = g.name,
		Login_name = m.name,
		Default_db = m.dbname
			from sysusers u, sysusers g, sysalternates a,
				master.dbo.syslogins m
			where u.suid *= m.suid
				and u.gid *= g.uid
				and u.uid <= 16383 and u.uid != 0
				and a.suid = suser_id(@name_in_db)
				and a.altsuid = u.suid

	else


	    select Alias_name = convert(char(17), u.name), ID_in_db = u.uid,
		Group_name = convert(char(17), g.name),
		Login_name = convert(char(17), m.name),
		Default_db = convert(char(15), m.dbname)
			from sysusers u, sysusers g, sysalternates a,
				master.dbo.syslogins m
			where u.suid *= m.suid
				and u.gid *= g.uid
				and u.uid <= 16383 and u.uid != 0
				and a.suid = suser_id(@name_in_db)
				and a.altsuid = u.suid


	return (0)
end

/* 17703, "The name supplied is not a user, group, or aliased." */
exec sp_getmessage 17703, @msg out
print @msg

return (1)
go
exec sp_procxmode 'sp_helpuser', 'anymode'
go
grant execute on sp_helpuser to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_locklogin')
begin
	drop procedure sp_locklogin
end
go
print "Installing sp_locklogin"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	5.0	1.0	10/22/91	sproc/src/locklogin */

/*
** Messages for "sp_locklogin"	17912
**
** 17260, "Can't run %1! from within a transaction."
** 17880, "No such account -- nothing changed."
** 17912, "Error in locking the account."
** 17913, "Locked account(s):"
** 17914, "Account unlocked."
** 17915, "Warning:  the specified account is currently active."
** 17916, "Cannot lock the last remaining unlocked SSO login."
** 18045, "Cannot lock the last remaining unlocked SA login."
** 17917, "Error: locktype must either be 'lock' or 'unlock'."
** 17918, "Nothing changed."
** 17919, "Account locked."
*/

create procedure sp_locklogin
@loginame varchar(30) = NULL,		/* name of the login to be locked */
@locktype varchar(30) = NULL		/* "locked" or "unlock"            */
as
declare @suid int			/* suid of login to be modified   */
declare @msg	varchar(250)		/* message text */
declare @dummy int

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/* 17260, "Can't run %1! from within a transaction." */
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_locklogin"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
** Check if user has sa or sso role.  Must do this through show_role(),
** because we don't want to print any messages or do auditing yet.
*/

if (charindex("sa_role", show_role()) = 0 and
    charindex("sso_role", show_role()) = 0)
begin
	/*
	** Call proc_role() with each role to print a message and send the
	** failure audit records if necessary.
	*/
	select @dummy = proc_role("sa_role")
	select @dummy = proc_role("sso_role")
	return (1)
end
else
begin
	/*
	** Call proc_role() with each role that the user has in order to
	** send the success audit records.  Note that this could mean 1 or
	** 2 audit records.
	*/
	if (charindex("sa_role", show_role()) > 0)
		select @dummy = proc_role("sa_role")
	if (charindex("sso_role", show_role())> 0)
		select @dummy = proc_role("sso_role")
end

if @loginame is NULL and @locktype is NULL
begin
	/*
	** 17913, "Locked account(s):"
	*/
	exec sp_getmessage 17913, @msg output
	print @msg
	select name
	from master.dbo.syslogins
	where ((status & 2) = 2) /* LOGIN_LOCKED */
	return (0)
end

/*  Check if the account exists */
select @suid = suid
	from master.dbo.syslogins
	where name = @loginame
if @suid is NULL
begin
	/*
	** 17880, "No such account -- nothing changed."
	*/
	exec sp_getmessage 17880, @msg output
	print @msg
	return (1)
end

if ((@locktype != "unlock") and (@locktype != "lock"))
begin
	/*
	** 17917, "Error: locktype must either be 'lock' or 'unlock'."
	*/
	exec sp_getmessage 17917, @msg output
	print @msg
	/*
	** 17918, "Nothing changed."
	*/
	exec sp_getmessage 17918, @msg output
	print @msg
	return (1)
end
else if @locktype = "unlock"
begin

	/* Unlock any existing account */
	update master.dbo.syslogins
	set status = status & (~2)	/* not LOGIN_LOCKED */
	where suid = @suid
	/*
	** 17914, "Account unlocked."
	*/
	exec sp_getmessage 17914, @msg output
	print @msg
	return (0)
end

/*
**  When it comes down to here, it must be the complicated "lock" case.
*/

/*
**  If the account to be locked is active, go ahead and try to lock it,
**  but issue a warning message.
*/
if exists (select * from master.dbo.sysprocesses where suid = @suid)
begin
	/*
	** 17915, "Warning: the specified account is currently active."
	*/
	exec sp_getmessage 17915, @msg output
	print @msg

	/* FALL THROUGH */
end

/*
**  We can't allow the last unlocked SSO and SA logins to be locked, because
**  the system would then become hosed.  So check and prevent both cases.
*/
if ((select count(suid) from master.dbo.syslogins
	where (status & 2) = 0 and suid in
		(select suid from master.dbo.sysloginroles where srid = 1)) = 1) and
    ((select count(suid) from master.dbo.sysloginroles
	where suid = @suid and srid = 1) = 1)
begin
	/* 17916, "Cannot lock the last remaining unlocked SSO login." */
	exec sp_getmessage 17916, @msg output
	print @msg
	return (1)
end

if ((select count(suid) from master.dbo.syslogins
	where (status & 2) = 0 and suid in
		(select suid from master.dbo.sysloginroles where srid = 0)) = 1) and
    ((select count(suid) from master.dbo.sysloginroles
	where suid = @suid and srid = 0) = 1)
begin
	/* 18045, "Cannot lock the last remaining unlocked SA login." */
	exec sp_getmessage 18045, @msg output
	print @msg
	return (1)
end

/*  Feel free to lock the account */
update master.dbo.syslogins
	set status = status | 2 /* LOGIN_LOCKED */
	where suid = @suid
/*
**  Check @@rowcount when it works
*/
if @@rowcount = 1
begin
	/*
	** 17919, "Account locked."
	*/
	exec sp_getmessage 17919, @msg output
	print @msg
	return (0)
end
else
begin
	/*
	** 17912, "Error in locking the account."
	*/
	exec sp_getmessage 17912, @msg output
	print @msg
	return (1)
end
go
exec sp_procxmode 'sp_locklogin', 'anymode'
go
grant execute on sp_locklogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_displaylogin')
begin
	drop procedure sp_displaylogin
end
go
print "Installing sp_displaylogin"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	5.0	1.0	10/22/91	sproc/src/displaylogin */

/*
** Messages for "sp_displaylogin"     17943
**
** 17231, "No login with the specified name exists."
** 17943, "Suid: %1!"
** 17944, "Loginame: %1!"
** 17945, "Fullname: %1!"

** 17949, "Locked: %1!"
** 17950, "Date of Last Password Change: %1!"
** 17951, "Configured Roles:"
*/

create procedure sp_displaylogin 
@loginame varchar(30) = NULL as

declare @suid int			/* suid of person to display */
declare @fullname varchar(30)		/* login owner's full name */

declare @auths    int
declare @status   int
declare @pwdate   datetime
declare @thisauth int
declare @authname varchar(30)
declare @msg      varchar(250)
declare @msg_yes_or_no  varchar(250)
declare @local_msgbuf char(30)
declare @dummy int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

if @loginame is NULL
	select @loginame = suser_name()

/*
**  Only accounts with SSO authorization

**  can display other login info.
**  Call proc_role() with the required SSO role.
*/


if (@loginame != suser_name ())
begin
	/* 
	** check if we are the sa or the sso. If show_role() 
	** does not find both "sa_role" and the "sso_role"
	** then we call proc_role() with each role to print
	** a messae and send the failure audit records if 
	** necessary.
	** Note: show_role does not print any message.
	*/
	if ( charindex ("sa_role", show_role())  = 0  and
	     charindex ("sso_role", show_role()) = 0  )
	begin
		select @dummy = proc_role("sa_role")	
		select @dummy = proc_role("sso_role")	
		return(1)	
	end
	else
	begin
		/*
		** Call proc_role() with each role that the user has 
		** in order to send the success audit records.  
		** Note that this could mean 1 or 2 audit records.
		*/
		if (charindex("sa_role", show_role()) > 0)
			select @dummy = proc_role("sa_role")
		if (charindex("sso_role", show_role())> 0)
			select @dummy = proc_role("sso_role")
	end
end


select @suid = suid, 
	@fullname = fullname,

	@status   = status,
	@pwdate	  = pwdate
from master.dbo.syslogins
where name = @loginame
if @suid is NULL
begin
	/*
	** 17231, "No login with the specified name exists."
	**	(was "Invalid Login user.")
	*/
	exec sp_getmessage 17231, @msg output
	print @msg
	return (1)
end

/* Output the messages */
/* 17943, "Suid: %1!" */
exec sp_getmessage 17943, @msg output
select @local_msgbuf = convert (char(10), @suid)
print @msg, @local_msgbuf
/* 17944, "Loginame: %1!" */
exec sp_getmessage 17944, @msg output
print  @msg, @loginame

begin
	/* 17945, "Fullname: %1!" */
	exec sp_getmessage 17945, @msg output
	print  @msg, @fullname
end


/*
** 17951, "Configured Roles:"
*/
exec sp_getmessage 17951, @msg output

select @thisauth = min(srid)
	from master.dbo.sysloginroles
	where suid = @suid
while (@thisauth is not NULL)
begin
	select @authname = name
		from master.dbo.syssrvroles
		where srid = @thisauth
	if @authname is not NULL
	begin
		select @msg = @msg + " " + @authname
	end
	select @thisauth = min(srid)
		from master.dbo.sysloginroles
		where suid = @suid and srid > @thisauth
end
print  @msg

select @msg = "Locked: "

if (@status & 2) = 2 /* LOCKED */
	begin
		/* 17011, "yes" */
		exec sp_getmessage 17011, @msg_yes_or_no output
	end
else
	begin
		/* 17010, "no" */
		exec sp_getmessage 17010, @msg_yes_or_no output
	end
/*
** 17949, "Locked: %1!"
*/
exec sp_getmessage 17949, @msg output
select @local_msgbuf = upper(@msg_yes_or_no)
print @msg, @local_msgbuf



begin
	/* Date of Last Password Change */
	/*
	** 17950, "Date of Last Password Change: %1!"
	*/
	exec sp_getmessage 17950, @msg output
	select @local_msgbuf =  convert(char(20), @pwdate)
	print @msg, @local_msgbuf
end
	
return (0)

go
exec sp_procxmode 'sp_displaylogin', 'anymode'
go
grant execute on sp_displaylogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addalias')
begin
	drop procedure sp_addalias
end
go
print "Installing sp_addalias"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/addalias */

/*
** Messages for "sp_addalias"           17230
**
** 17231, "No login with the specified name exists."
** 17232, "No user with the specified name exists in the current database."
** 17233, "'%1!' is already a user in the current database."
** 17234, "The specified user name is already aliased."
** 17235, "Alias user added."
*/
create procedure sp_addalias
@loginame varchar(30),		/* the name of the pretender */
@name_in_db varchar(30)		/* who the pretender wants to pretend to be */
as

declare @suid int		/* the suid of the pretender */
declare @asuid int		/* the suid of the person to impersonate */
declare @msg varchar(250)
declare @name   varchar(30)

set transaction isolation level 1
if @@trancount = 0
begin
	set chained off
end
/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
	return(1)

/*
**  Make sure that the pretender has an account.
*/
select @suid = suid
	from master.dbo.syslogins
where name = @loginame

if @suid is NULL
begin
	/* 17231, "No login with the specified name exists." */
	exec sp_getmessage 17231, @msg output
	print @msg
	return (1)
end

/*
**  Get the suid of the person we want to pretend to be.
**  User ids range from -16383 to +16383 and group ids are > 16383.
*/
select @asuid = suid
	from sysusers
where name = @name_in_db
	and uid <= 16383

/*
**  Does the user to be impersonated exist in the current database?
*/
if @asuid is NULL
begin
	/* 
	** 17232, "No user with the specified name exists in the
	** current database." 
	*/
	exec sp_getmessage 17232, @msg out
	print @msg
	return (1)
end

/*
**  Does the login to do the impersonating already a user in the current db?
*/
if exists (select *
		from sysusers
			where suid = @suid)
begin
	/* 17233, "'%1!' is already a user in the current database." */
        select @name = name
                from sysusers
                        where suid = @suid
	exec sp_getmessage 17233, @msg out
        print @msg, @name
        return (1)
end

/*
** Is the person already aliased to a user?
*/
if exists (select *
		from sysalternates
	where suid = @suid)
begin
	/* 17234, "The specified user name is already aliased." */
	exec sp_getmessage 17234, @msg out
	print @msg
	return (1)
end

/*
**  Add the alias.
*/
insert into sysalternates (suid, altsuid)
	values (@suid, @asuid)

/* 17235, "Alias user added." */
exec sp_getmessage 17235, @msg out
print @msg

return (0)
go
exec sp_procxmode 'sp_addalias', 'anymode'
go
grant execute on sp_addalias to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addgroup')
begin
	drop procedure sp_addgroup
end
go
print "Installing sp_addgroup"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.2	28.1	05/14/90	sproc/src/addgroup */

/*
** Messages for "sp_addgroup"           17240
**
** 17240, "'%1!' is not a valid name."
** 17241, "A user with the specified group name already exists."
** 17242, "A group with the specified name already exists."
** 17243, "New group added."  
*/

create procedure sp_addgroup
@grpname varchar(30)			/* new group name */
as

declare @gid int			/* group id */
declare @msg varchar(250)
declare @returncode int



set transaction isolation level 1
if @@trancount = 0
begin
	set chained off
end

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
	return(1)

/*
**  Check to see that the @grpname is valid.
*/
if valid_name(@grpname) = 0
begin

	/*
	** 17240, "'%1!' is not a valid name."
	*/ 
	exec sp_getmessage 17240,  @msg out
	print @msg, @grpname
	return 1
end

/*
**  See if the new group name is already being used as a user or group name.
*/
select @gid = uid
	from sysusers
where name = @grpname

/*
**  User ids range from -16383 to +16383 and group ids are > 16383.
*/
if @gid is not null
begin

	if @gid != 0 and @gid <= 16383
	begin
		/*
		** 17241, "A user with the specified group name already exists."
		*/
		exec sp_getmessage 17241,  @msg out
		print @msg
	end
	else
	begin
		/*
		** 17242, "A group with the specified name already exists."
		*/
		exec sp_getmessage 17242,  @msg out
		print @msg
	end
	return (1)
end

/*
**  Now get the group id for the new group.  It is the current maximum group
**  number + 1.  If this is the first group use the lowest possible group id
**  -- 16384.
*/
select @gid = max(uid)+1
	from sysusers

/*
**  This is the first group.
*/
if @gid < 16384 or @gid is NULL
	select @gid = 16384

/*
**  Create the group.
*/
insert into sysusers (uid, suid, gid, name, environ)
values (@gid, -@gid, @gid, @grpname, "")

/*
** 17243, "New group added."  
*/
exec sp_getmessage 17243,  @msg out
print @msg

return (0)
go
exec sp_procxmode 'sp_addgroup', 'anymode'
go
grant execute on sp_addgroup to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_password')
begin
	drop procedure sp_password
end
go
print "Installing sp_password"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/* 	4.8	1.1	06/14/90	sproc/src/password */

/*
** Messages for "sp_password"           17720
**
** 17260, "Can't run %1! from within a transaction."
** 17880, "No such account -- nothing changed."
** 17720, "Error:  Unable to set the Password."
** 17721, "Password correctly set."
*/

create procedure sp_password
@caller_password varchar(30) = NULL,	/* the current password of caller */
@new_password    varchar(31) = NULL,	/* the new password of the target acct*/
					/* a length of 31 is required to test if
					** user entered a passwd > 30 chars.
					*/
@loginame        varchar(30) = NULL	/* user to change password on */
as

declare @returncode int
declare @msg  varchar(250)

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_password"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Encrypt and store the input @new_password.
**  @caller_password will be checked against the password of the caller.
**  set_password() builtin will print out nice messages.
**
*/
select @returncode = set_password(@caller_password, @new_password, @loginame)
if (@returncode = 0)
begin
	/*
	** 17720, "Error:  Unable to set the Password."
	*/
	exec sp_getmessage 17720, @msg output
	print @msg
	return (1)
end
else
begin
	/*
	** 17721, "Password correctly set."
	*/
	exec sp_getmessage 17721, @msg output
	print @msg
	return (0)
end

go
exec sp_procxmode 'sp_password', 'anymode'
go
grant execute on sp_password to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addlogin')
begin
	drop procedure sp_addlogin
end
go
print "Installing sp_addlogin"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/addlogin */

/*
** Messages for "sp_addlogin"           17260
**
** 17240, "'%1!' is not a valid name." 
** 17201, "'%1!' is not an official language name from Syslanguages." 
** 17260, "Can't run %1! from within a transaction."
** 17262, "A user with the specified login name already exists."
** 17263, "Database name not valid -- login not added."
** 17264, "New login created."
** 17266, "All logins have been assigned. No more logins can be added at this time."
*/

create procedure sp_addlogin
@loginame varchar(30),			/* login name of the new user */

@passwd varchar(31) = NULL,		/* password of the new user */
					/* a length of 31 is required to test if
					** user entered a passwd > 30 chars.
					*/

@defdb varchar(30) = "master",		/* default db for the new user */
@deflanguage varchar(30) = NULL,	/* default language for the new user */
@fullname varchar(30) = NULL		/* account owner's full name */
as

declare @msg varchar(250)
declare @suid   int			/* 
					** suid corresponding to insert
					** slot in syslogins
					*/

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_addlogin"
	return (1)
end
else
begin
	set chained off
end
set transaction isolation level 1


/* check if user has sso role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/
if (proc_role("sso_role") = 0)
	return (1)



/*
**  Check to see that the @loginame is valid.
*/
declare @returncode	int
if valid_name(@loginame) = 0
begin
	/*
	** 17240, "'%1!' is not a valid name." 
	*/
	exec sp_getmessage 17240, @msg output
	print @msg, @loginame
	return 1
end

/* 
**  Check to see that the @deflanguage is valid.
*/
if @deflanguage is not null
begin
	select @returncode = 0
	execute @returncode = sp_validlang @deflanguage
	if @returncode != 0
	begin
		/* Us_english is always valid */
		if @deflanguage != "us_english"
		begin
			/*
			** 17201, "'%1!' is not an official language name from Syslanguages." 
			*/
			exec sp_getmessage 17201, @msg output
			print @msg, @deflanguage
			return @returncode
		end
	end
end

/*
**  Make sure the login doesn't already exist.
*/
if exists (select *
	from master.dbo.syslogins
	where name = @loginame)
begin
	/*
	** 17262, "A user with the specified login name already exists."
	*/
	exec sp_getmessage 17262, @msg output
	print @msg
	return (1)
end

/*
**  Check that the database name is valid.
**  If it was specified as NULL then default it to "master".  Note that this
**  can happen for 'sp_addlogin peter, password, null, null, "peter rabbit"'
**  but not for 'sp_addlogin peter, password, @fullname = "peter rabbit"'.
*/
if @defdb = NULL
begin
	select @defdb = "master"
end
if not exists (select *
	from master.dbo.sysdatabases
	where name = @defdb)
begin
	/*
	** 17263, "Database name not valid -- login not added."
	*/
	exec sp_getmessage 17263, @msg output
	print @msg
	return (1)
end

select @suid = max(suid) + 1
		from master.dbo.syslogins

if @suid > 32767
/* Check for the holes */
begin
	/* We start search from suid=3 to avoid reusing sa or probe suids */
	select @suid = 3
	while exists ( select * from master.dbo.syslogins
			where suid = @suid )
	begin
		select @suid = @suid +1
		if @suid >= 32767
		begin
			/*
			** 17266, "All logins have been assigned.
			** No more logins can be  added at this time."
			*/
			raiserror 17266
			return (1)
		end
	end
end

/*
**  Create the login.  Lock the account temporarily and
**  Put in a dont-care NULL as password.

*/


insert into master.dbo.syslogins (suid, status, accdate, totcpu, totio,
        spacelimit, timelimit, resultlimit,
        dbname, name, password, language,
        pwdate, audflags, fullname)
    values (@suid, 2, getdate(), 0, 0, 0, 0, 0,
        @defdb, @loginame, NULL, @deflanguage,
        getdate(), 0, @fullname)



/*
**  Encrypt and store the input password
*/
execute @returncode = sp_password NULL, @passwd, @loginame
if @returncode = 0
begin
	/* UN-lock the account after successful update */
	execute @returncode = sp_locklogin @loginame, "unlock"

	if @returncode = 0
	begin
		/*
		** 17264, "New login created."
		*/
		exec sp_getmessage 17264, @msg output
		print @msg
	end
end
else
begin
	/* Delete the account */
	delete from master.dbo.syslogins where name = @loginame
end
return (@returncode)


go
exec sp_procxmode 'sp_addlogin', 'anymode'
go
grant execute on sp_addlogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addtype')
begin
	drop procedure sp_addtype
end
go
print "Installing sp_addtype"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

/*
** Messages for "sp_addtype"            17300
**
** 17300, "Usage: sp_addtype name, 'datatype' [,null | nonull | identity]"
** 17301, "'%1!' is not a valid type name."
** 17302, "A type with the specified name already exists."
** 17303, "Physical datatype does not exist."
** 17304, "User-defined datatypes based on the 'timestamp' datatype are not allowed."
** 17305, "Physical datatype does not allow nulls."
** 17306, "Physical type is fixed length. You cannot specify the length."
** 17307, "You must specify a length with this physical type.
** 17308, "Illegal length specified -- must be between 1 and 255."
** 17309, "Type added."
** 17751, "Illegal precision specified -- must be between 1 and 38."
** 17752, "Illegal scale specified -- must be less than precision and positive."
** 17754, "Illegal precision specified -- must be between 1 and 48."
*/

create procedure sp_addtype
@typename varchar(30),		/* name of user-defined type */
@phystype varchar(80),		/* physical system type of user-defined type */
@nulltype varchar(8) = "1"	/* default is database 'allow null' default */
as

declare @len int		/* length of user type */
declare @type tinyint		/* typeid of physical type */
declare @tlen tinyint		/* length of physical type */
declare @typeid smallint	/* user typeid of physical type */
declare @var bit		/* is physical type variable length? */
declare @nonull bit		/* default is to allow NO NULLs */
declare @nullegal bit		/* does physical type allow NULLs? */
declare @msg varchar(250)
declare @prec int		/* precision of the datatype */
declare @scale int		/* scale of the datatype */
declare @tprec tinyint		/* precision of the datatype read from systypes */
declare @tscale tinyint		/* scale of the datatype read from systypes */
declare @u_identity tinyint	/* does user type have identity property? */
declare @hierarchy tinyint	/* hierarchy level of the datatype */
declare @index int		/* index of blank char in the string of datatype*/
declare @rest varchar(80)	/* string that holds the temporay portion of the datatype.*/
declare @nulldefault int	/* 'allow null' database default */
declare @nationalchar int	/* national character type is specified */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1
/*
**  Does the user type allow NULLs?  Now, the default is to 
**  use the 'allow null' option setting for the current database.
**  This is the same default the create table statement uses.
*/
if @nulltype = "1"
begin
	/*
	** Get database 'allow null default. @nulldefault = 0
	** means 'not null allowed' is database default.
	**
	** 17069, "allow nulls by default"
	**
	** Make sure not to get the internationalized message
	** by "us_english" parameter, even if client is using
	** an alternative language. This is because spt_values
	** has an us_english message only, even if an alternative
	** language is installed.
	*/

	exec sp_getmessage 17069, @msg output, "us_english"

	select @nulldefault = (a.number & b.status)
	from master.dbo.spt_values a, master.dbo.sysdatabases b
	where a.name = @msg and b.name = db_name()
	if (@nulldefault = 0)
		select @nonull = 1
	else
		select @nonull = 0
	select @u_identity = 0
end
else if lower(@nulltype) = "null" or @nulltype is null
begin
	select @nonull = 0
	select @u_identity = 0
end
else if lower(@nulltype) = "identity"
begin
	select @nonull = 1
	select @u_identity = 1
end
else if lower(@nulltype) in ("not null" , "nonull")
begin
	select @nonull = 1
	select @u_identity = 0
end
else
begin
	/*
	** 17300, "Usage: sp_addtype name, 'datatype' [,null | nonull | identity]"
	*/
	exec sp_getmessage 17300, @msg output
	print @msg
	return (1)
end

/*
**  Check to see that the @typename is valid.
*/
if valid_name(@typename) = 0
begin
	/*
	** 17301, "'%1!' is not a valid type name."
	*/
	exec sp_getmessage 17301, @msg output
	print @msg, @typename
	return (1)
end

/*
**  Check to see if the type already exists.
*/
if exists (select *
		from systypes
   	where name = @typename)
begin
	/*
	** 17302, "A type with the specified name already exists."
	*/
	exec sp_getmessage 17302, @msg output
	print @msg
	return (1)
end

/* Make physical typename all lower case to ensure case insensitivity. */
select @phystype = lower(@phystype)

/* initialize the length to be NULL first. */
select @len = NULL
/*
** If precision and scale were given with the type extract them
*/
if @phystype like "_%(_%,_%)"
begin
	select @prec = convert(int, substring(@phystype,
		charindex("(",@phystype) + 1,
		charindex(",",@phystype) - 1 - charindex("(",@phystype)))

	select @scale = convert(int, substring(@phystype,
		charindex(",",@phystype) + 1,
		charindex(")",@phystype) - 1 - charindex(",",@phystype)))
	/*
	** Extract the physical type name 
	*/
	select @phystype = substring(@phystype, 1,
		   charindex("(", @phystype) - 1)
end
else

/*
**  If a length was given with the user datatype, extract it.
**  This could also be the precision, at this time assume it's the length
**  we'll decide later whether it's the length or precision.
*/
if @phystype like "_%(_%)"
begin
	select @len = convert(int, substring(@phystype,
		charindex("(",@phystype) + 1,
		charindex(")",@phystype) - 1 - charindex("(",@phystype)))

	/*
	** Extract the physical type name 
	*/
	select @phystype = substring(@phystype, 1,
		   charindex("(", @phystype) - 1)
end

/*
** Now, squeezes all consective space characters in the datatype string 
** into one single space character. By doing this, sp_addtype can recognize
** datatype, such as "   national      char    varying".
*/
select @phystype = ltrim(rtrim(@phystype))
select @rest = @phystype
select @phystype = NULL
select @index = charindex(' ', @rest) 
while (@index != 0)
begin
	select @phystype = @phystype + substring(@rest, 1, @index -1) + ' '
	select @rest = ltrim(stuff(@rest, 1, @index, ''))
	select @index = charindex(' ', @rest)
end
select @phystype = rtrim(@phystype + @rest)

/* 
** Assgin value to @nationalchar before do the datatype mapping,
** this value will be used when calculate the actual storage length.
*/

if (@phystype in ("nchar", "nvarchar", "national char", "national character",
	"nchar varying", "national char varying", "national character varying"))
begin
	select @nationalchar = 1
end
else
begin
	select @nationalchar = 0
end

/*
**  Do the following datatypes mapping now.
**  "character"--> "char"; "nchar"--> "char"; 
**  "[national] char[acter] varying"--> "varchar"; "nchar varying"-->"varchar";
**  "dec" ---> "decimal";  "integer"---> "int"; "double precision" --> "float";
**  Map the default length of datatype "char" ,"varchar", "binary", "varbinary"
**  and their various synonyms to 1.
*/
if (@phystype in ("char", "character", "nchar", "national char", 
	"national character"))
begin
	select @phystype = "char"
	/*
	** If len is not specified, supply the default length to be 1.
	*/
	if (@len is NULL) select @len = 1	
end
else
if (@phystype in ("varchar", "nvarchar", "nchar varying", "char varying", 
   "character varying", "national char varying", "national character varying"))
begin
	select @phystype = "varchar"
	/*
	** If len is not specified, supply the default length to be 1.
	*/
	if (@len is NULL) select @len = 1	
end
if ((@phystype in ("binary", "varbinary")) and (@len is NULL))
	/*
	** If len is not specified, supply the default length to be 1.
	*/
	select @len = 1
else
if (@phystype = "integer") select @phystype = "int"
else
if (@phystype = "double precision") select @phystype = "float"
else
if (@phystype = "dec") select @phystype = "decimal"
else
	/*
	** If len for float datatype is specified, then the range must
	** be between 1 to 48. If len specified is <= 15, map the type
	** to real, otherwise map the type to float.
	*/
if (@phystype = "float") and (@len is not NULL)
begin
	if (@len  < 1 or @len > 48)
	begin
		exec sp_getmessage 17754, @msg output
		print @msg
		return (1)
	end
	else
	begin
		if (@len < = 15) select @phystype = "real" 		
		select @len = NULL
	end
end

/*
**  Make sure that the physical type exists and get its characteristics.
**  DataServer physical types have a usertype < 100 and are owned by the
**  dbo (userid = 1).
**  Datatypes datetimn, decimaln, floatn, intn, moneyn and numericn are 
**  not supported to users. Those datatypes must be invisible to users.
*/
select @type = type, @tlen = length, @typeid = usertype,
	@var = variable, @nullegal = allownulls, @tprec = prec,
	@tscale = scale, @hierarchy = hierarchy
from systypes
	where usertype < 100 and name = @phystype and uid = 1
	  and @phystype not in ('datetimn', 'decimaln', 'floatn',
				'intn', 'moneyn', 'numericn')

if @type is NULL
begin
	/*
	** 17303, "Physical datatype does not exist."
	*/
	exec sp_getmessage 17303, @msg output
	print @msg
	return (1)
end

/*
**  Disallow user-defined datatypes on timestamps.  This is done because
**  a timestamp is not a basic type but is really a binary.  There is,
**  therefore, no way to tell if a user-defined datatype is mapped to
**  a binary or a timestamp.  Timestamps can't have rules or defaults.
*/
if @phystype = "timestamp"
begin
	/*
	** 17304, "User-defined datatypes based on the 'timestamp' datatype are not allowed."
	*/
	exec sp_getmessage 17304, @msg output
	print @msg
	return (1)
end

/*
**  Check if the NULL status of the user type is consistent with the NULL status
**  of the physical type.  Here are the possible cases.
**
**		   physical type
**		  NULLs	  NONULLs
**	        -----------------
** user	NULLs	|  ok	|  no
** type NONULLs	|  ok	|  ok
*/
if @nonull = 0 and @nullegal = 0
begin
	/*
	** 17305, "Physical datatype does not allow nulls."
	*/
	exec sp_getmessage 17305, @msg output
	print @msg
	return (1)
end

/*
**  We'll use the variable @nullegal when we update the systypes table
**  so we need to set it to reflect if NULLs are allowed (@nonull = 0)
**  or NO NULLs are allowed (@nonull = 1).
*/
if @nonull = 0
begin
	select @nullegal = 1
end
else
begin
	select @nullegal = 0
end

/* Decide about precision, scale, length 
** First check fro NUMERIC, DECIMAL
*/
if (@typeid = 26) or (@typeid = 10) 
begin
	/* Type is NUMERIC or DECIMAL */
	
	if @len > 0
	begin
		/* Length is really the precision 
		** Since no scale is specified then scale
		** is minimum(Default, precision). Default = 4
		*/
		select @prec = @len
		select @scale = 0

	end
	else
	begin
		if (@prec is NULL)
		begin
			select @prec = 18
			select @scale = 0
		end
	end

	

	if (@prec > 38) or (@prec < 1)
	begin
		/*
		** 17751, "Illegal precision specified -- must be between 1 and 38."
		*/
		exec sp_getmessage 17751, @msg output
		print @msg
		return (1)
	end

	if (@scale > @prec) or (@scale < 0)
	begin
		/*
		** 17752, "Illegal scale specified -- must be less than precision 
		** 	   and positive."
		*/
		exec sp_getmessage 17752, @msg output
		print @msg
		return (1)
	end
	
	/* Compute length from precision */
	if (@prec <= 2)	
		select @len = 2
	
	if (@prec > 2) and (@prec <= 4)
		select @len = 3

	if (@prec > 4) and (@prec <= 7)
		select @len = 4

	if (@prec > 7) and (@prec <= 9)
		select @len = 5

	if (@prec > 9) and (@prec <= 12)
		select @len = 6

	if (@prec > 12) and (@prec <= 14)
		select @len = 7

	if (@prec > 14) and (@prec <= 16)
		select @len = 8

	if (@prec > 16) and (@prec <= 19)
		select @len = 9

	if (@prec > 19) and (@prec <= 21)
		select @len = 10

	if (@prec > 21) and (@prec <= 24)
		select @len = 11

	if (@prec > 24) and (@prec <= 26)
		select @len = 12

	if (@prec > 26) and (@prec <= 28)
		select @len = 13

	if (@prec > 28) and (@prec <= 31)
		select @len = 14

	if (@prec > 31) and (@prec <= 33)
		select @len = 15

	if (@prec > 33) and (@prec <= 36)
		select @len = 16

	if (@prec > 36) and (@prec <= 38)
		select @len = 17
end
else
begin
/*
**  Typeids 1 (char), 2 (varchar), 3 (binary), 4 (varbinary) 
**  24 (nchar) and 25 (nvarchar) are the
**  only ones which allow a length to be specified.
*/
if @typeid > 4 and @typeid not in (24, 25) 
begin
	/*
	**  We can't use a length and we got one.
	*/
	if @len > 0
	begin
		/*
		** 17306, "Physical type is fixed length. You cannot specify the length."
		*/
		exec sp_getmessage 17306, @msg output
		print @msg
	   	return (1)
	end

	/*
	**  Use the fixed length of the physical type.
	*/
	select @len = @tlen
end
else
begin
	/*
	**  We need a length and we didn't get one.
	*/
	if @len is NULL
	begin
		/*
		** 17307, "You must specify a length with this physical type. 
		*/
		exec sp_getmessage 17307, @msg output
		print @msg
		return (1)
	end

	/*
	** If "nchar" or "nvarchar" is specified, caluculate the real length
	*/

	if @nationalchar = 1
		select @len = @len * @@ncharsize

	if @len <= 0 or @len > 255
	begin
		/*
		** 17308, "Illegal length specified -- must be between 1 and 255."
		*/
		exec sp_getmessage 17308, @msg output
		print @msg
		return (1)
	end


end
end

/*  Check to make sure only numeric(x,0) types have identity property. */
if @u_identity = 1
begin
	if @phystype != "numeric" or @scale != 0
	begin
		/*
		** 17755, "User types with the identity property must be numeric
		**         with a scale of 0."
		*/
		exec sp_getmessage 17755, @msg output
		print @msg
		return(1)
	end
end

/*
**  Finally, get the maximum existing user type so we use it + 1 for this
**  new type.
*/
select @typeid = max(usertype)
	from systypes

/*
**  There are no user defined types yet so use the first number (101).
*/
if @typeid < 100
	select @typeid = 100

insert systypes (uid, variable, type, length, tdefault,
	domain, name, usertype, allownulls, prec, scale, ident, hierarchy)
select user_id(), @var, @type, @len, 0, 0, @typename, @typeid + 1, @nullegal,
@prec, @scale, @u_identity, @hierarchy

/*
** 17309, "Type added."
*/
exec sp_getmessage 17309, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_addtype', 'anymode'
go
grant execute on sp_addtype to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addumpdevice')
begin
	drop procedure sp_addumpdevice
end
go
print "Installing sp_addumpdevice"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/addumpdevice */

/*
** Messages for "sp_addumpdevice"       17310
**
** 17260, "Can't run %1! from within a transaction." 
** 17240, "'" + @logicalname + "' is not a valid name." 
** 17310, "Unknown device type.  Use 'disk' or 'tape'."
** 17311, "@logicalname may not be NULL."
** 17312, "@physicalname may not be NULL."
** 17314, "Device with same logical name already exists."
** 17317, "Please specify media capacity in megabytes (1 MB minimum)."
** 17318, "WARNING: specified size parameter is not used for the disk device type."
** 17319, "'Disk' device added."
** 17320, "'Tape' device added."
** 17321, "WARNING: physical device name '%1!' is not unique." 
*/
create procedure sp_addumpdevice
@devtype	varchar(10),		/* disk, tape, or special */
@logicalname	varchar(30),		/* logical name of the device */
@physicalname	varchar(127),		/* physical name of the device */
@tapesize	int = NULL		/* capacity of tape in MB */
as

declare @status smallint		/* status bits for device */
declare @msg varchar(250)
declare @tapeblocksize int
declare @name varchar(30)
declare @cntrltype smallint

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	select @name = "sp_addumpdevice"
	exec sp_getmessage 17260, @msg output
	print @msg, @name
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  Check to see that the @logicalname is valid.
*/
if valid_name(@logicalname) = 0
begin
	/*
	** 17240, "'" + @logicalname + "' is not a valid name." 
	*/
	exec sp_getmessage 17240, @msg output
	print @msg, @logicalname
	return (1)
end

/*
**  The rules for updating sysdevices are as follows:
**	devtype - may be disk or tape.  If disk then
**			cntrltype will be 2,
**		if tape then 3.  cntrltype is not used.
**	logicalname - may be any identifier but must be unique
**	physicalname - may be anything and doesn't have to be unique
**		If it contains illegal id characters, e.g., '/', then
**		it must be in quotes.
**	tapesize - for a tape device, this is the tape capacity in MB.  It
**		is ignored on VMS.
*/


/*
**  Check out the @devtype.
*/
select @devtype = lower(@devtype)

if (@devtype = "tape")
begin
	select @cntrltype = 3
end
else if (@devtype = "disk")
begin
	select @cntrltype = 2
end
else
begin
	/*
	** 17310, "Unknown device type.  Use 'disk' or 'tape'."
	*/
	exec sp_getmessage 17310, @msg output
	print @msg
	return (1)
end

/*
**  Check the args are not NULL.
*/
if @logicalname is NULL
begin
	/*
	** 17311, "@logicalname may not be NULL."
	*/
	exec sp_getmessage 17311, @msg output
	print @msg, @logicalname
	return
end
if @physicalname is NULL
begin
	/*
	** 17312, "@physicalname may not be NULL."
	*/
	exec sp_getmessage 17312, @msg output
	print @msg, @physicalname
	return
end

/*
**  Make sure that a device with @logicalname doesn't already exist.
*/
if exists (select *
		from master.dbo.sysdevices
			where name = @logicalname)
begin
	/*
	** 17314, "Device with same logical name already exists."
	*/
	exec sp_getmessage 17314, @msg output
	print @msg
	return (1)
end

/*
**  Always turn on the dump status bit.
*/
select @status = 16

/*
**  If @devtype is a tape then check to see if devstatus is 'skip'.
*/
if @devtype = "tape"
begin
	/*
	**  If this is not VMS, then @tapesize is required.
	*/
	if not exists (select *
			from master.dbo.spt_values
				where type = "E"
					and name = "vms")
	begin
		if @tapesize is NULL or @tapesize < 1
		begin
			/*
			** 17317, "Please specify media capacity in megabytes (1 MB minimum)."
			*/
			exec sp_getmessage 17317, @msg output
			print @msg
			return (1)
		end

                select @tapeblocksize = 32768

                select  @tapesize =
                        convert(int, ((@tapesize * 1048576.)
                                + @tapeblocksize -1) / @tapeblocksize)
	end
	else
	begin
		select @tapesize = 0
	end
end
else 
begin
	if @tapesize is not NULL
	begin
		/*
		** 17318, "WARNING: specified size parameter is not used for the disk device type."
		*/
		exec sp_getmessage 17318, @msg output	
		print @msg
	end
	select @tapesize = 0
end

/* Tell the server about the device by inserting into sysdevices */
insert into master.dbo.sysdevices (low, high, status, cntrltype, name, phyname)
	values (0, @tapesize, @status, @cntrltype, @logicalname, @physicalname)

if @devtype = "disk"
	/*
	** 17319, "'Disk' device added."
	*/
	exec sp_getmessage 17319, @msg output
else
	/*
	** 17320, "'Tape' device added."
	*/
	exec sp_getmessage 17320, @msg output

print @msg

/*
**  Warn about duplicate physical names.
*/
if (select count(*)
	from master.dbo.sysdevices
		where phyname = @physicalname) > 1
begin
	/*
	** 17321, "WARNING: physical device name '%1!' is not unique."   
	*/
	exec sp_getmessage 17321, @msg output
	print @msg, @physicalname
end

return (0)
go
exec sp_procxmode 'sp_addumpdevice', 'anymode'
go
grant execute on sp_addumpdevice to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addthreshold')
begin
	drop procedure sp_addthreshold
end
go
print "Installing sp_addthreshold"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_addthreshold"               17870
**
** 17870, "Table '%1!' does not exist in database '%2!' -- cannot add
**	  thresholds."
** 17871, "There is no segment named '%1!'."
** 17872, "This threshold is too close to one or more existing thresholds. 
** 		Thresholds must be no closer than 128 pages to each other."
** 17873, "Adding threshold for segment '%1!' at '%2!' pages."
** 17874, "A threshold at %1! pages is logically impossible for segment '%2!'.
**		Choose a value between %3! and %4! pages."
** 17875, "Only the DBO of database '%1!' or a user with System Administrator
**	   (SA) authorization may add, delete, or modify thresholds in that
**	   database."
** 17289, "Set your curwrite to the hurdle of current database."
** 18084, "A threshold at %1! pages for segment '%2!' is too close to the 
**	   maximum size of the database. Because of this, the threshold will 
**	   not fire more than once per SQL server re-boot. Modify the value 
**	   using sp_modifythreshold to be between %3! and %4! pages."
** 17876, "Warning: The specified threshold level is greater than the 
**         existing number of free pages on this segment."
*/

create procedure sp_addthreshold
@dbname		varchar(30),		/* current database name */
@segname	varchar(30),		/* segment name		*/
@free_space	int,			/* threshold level	*/
@proc_name	varchar(255)		/* threshold procedure	*/
as

declare	@segno	int,
	@segmap	int,
	@pagect	int,
	@hyst	int,
	@maxthpgct	int,
	@msg	varchar(255)

/*
** If we are under a user defined xact, disallow this since we may
** leave the dbtable's threshold cache out-of-sync if the end user
** rollbacks its xact.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_addthreshold"
	return (1)
end

set transaction isolation level 1    
set chained off

/*
** Make sure we are in the right database
*/
if (@dbname != db_name())
begin
	/*
	** 18031, "You are in the wrong database.  Say 'USE %1!', then run
	**         this procedure again."
	*/
	exec sp_getmessage 18031, @msg output
	print @msg, @dbname
	return (5)
end

/*
** Make sure our database is recent enough to contain Systhresholds
*/
if (select name from sysobjects
	where	name = 'systhresholds'
	  and	type = 'S')
   is NULL
begin
	/*
	** 17870, "Table '%1!' does not exist in database '%2!' -- cannot
	**	  add thresholds."
	*/
	exec sp_getmessage 17870, @msg output
	print @msg, "systhresholds", @dbname
	return (1)
end

/*
** Make sure the user (is the DBO) or (has "sa_role")
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
begin
	/*
	** 17875, "Only the DBO of database %1! or a user with System
	** Administrator (SA) authorization may add, delete, or modify
	** thresholds in that database."
	*/
	exec sp_getmessage 17875, @msg output
	print @msg, @dbname
	return (1)
end



/*
** Make sure the segment name is valid.
*/
select @segno = segment from syssegments where name = @segname
if @segno is NULL
begin
	/*
	** 17871, "There is no segment named '%1!'."
	*/
	exec sp_getmessage 17871, @msg output
	print @msg, @segname
	return (2)
end

/*
** Make sure the threshold fits within the segment
*/
select @segmap = power(2, @segno)
select @pagect = sum(size) from master..sysusages
where	dbid = db_id()
  and	segmap & @segmap = @segmap
if (@free_space < 0) or (@free_space > @pagect)
begin
	/*
	** 17874, "A threshold at %1! pages is logically impossible for
	** segment '%2!'.  Choose a value between %3! and %4! pages."
	*/
	exec sp_getmessage 17874, @msg output
	print @msg, @free_space, @segname, 0, @pagect
	return (4)
end

/*
** Make sure there is no existing threshold too close to this new one
*/
select @hyst = (2 * @@thresh_hysteresis) - 1
if exists (select free_space from systhresholds
	   where	segment = @segno
	     and	free_space between (@free_space - @hyst) and
					   (@free_space + @hyst))
begin
	/*
	** 17872, "This threshold is too close to one or more existing
	**	  thresholds.  Thresholds must be no closer than 128 pages
	**	  to each other."
	*/
	exec sp_getmessage 17872, @msg output
	print @msg
	select segment_name=@segname, free_space
	from systhresholds
	where	segment = @segno
	  and	free_space between (@free_space - @hyst) and
				   (@free_space + @hyst)
	return (3)
end

/*
** Make sure that the threshold is not too close to the maximum size of
** the database segment. If threshold value + @@thresh_hysteresis greater
** than maximum size of the database segment then the threshold will fire
** only once.
*/
select @maxthpgct = @pagect - @@thresh_hysteresis - 1
if (@pagect <= (@free_space + @@thresh_hysteresis))
begin
	/*
	** 18084, "A threshold at %1! pages for segment '%2!' is too 
	** close to the maximum size of the database. Because of this,
	** the threshold will not fire more than once per SQL server 
	** re-boot. Modify the value using sp_modifythreshold to be 
	** between %3! and %4! pages."
	*/
	exec sp_getmessage 18084, @msg output
	print @msg, @free_space, @segname, 0, @maxthpgct

	/* This is not an error, so raise a message and continue.  */
	
end

/*
** We do not validate the procedure name, since it might be in a different
** database or even in a remote server.  Thus, we have done all the tests
** we can.  Add the threshold.
*/

/*
** 17873, "Adding threshold for segment '%1!' at '%2!' pages."
*/
exec sp_getmessage 17873, @msg output
print @msg, @segname, @free_space

begin transaction insert_threshold



insert systhresholds values(@segno, @free_space, 0, @proc_name,
			    suser_id(), current_roles())


if @@error != 0
begin
	rollback transaction
	/*
	 ** 17877, "Insert of systhresholds row failed. "
	 */
  exec sp_getmessage 17877, @msg output
	print @msg
	return (1)
end

/*
** Last, rebuild the database threshold table
*/
dbcc dbrepair(@dbname, "newthreshold")

if @@error != 0
begin
	rollback transaction
	/*
	 ** 17878, "Rebuild of the database threshold table failed.
	 */
  exec sp_getmessage 17878, @msg output
	print @msg
	return (1)
end
/*
** If the specified threshold level(@free_space) is greater than the
** the existing number of free pages on the segment, the user should 
** be warned about this
*/


 if( (select sum( curunreservedpgs( dbid, lstart, unreservedpgs ) ) 
      from master.dbo.sysusages u, syssegments s
      where u.dbid = db_id()
        and u.segmap & power( 2, s.segment ) != 0
        and s.name = @segname) < @free_space )
 begin
	/* 17876, "Warning: The specified threshold level is greater 
	** than the existing number of free pages on this segment."   
        */
	exec sp_getmessage 17876, @msg output
	print @msg

	/* This is a warning, not an error. Hence raise a message
	   and continue. */
      
 end

commit transaction
return (0)
go
exec sp_procxmode 'sp_addthreshold', 'anymode'
go
grant execute on sp_addthreshold to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_modifythreshold')
begin
	drop procedure sp_modifythreshold
end
go
print "Installing sp_modifythreshold"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_modifythreshold"            17870
**
** 17870, "Table '%1!' does not exist in database '%2!' -- cannot add
**	  thresholds."
** 17871, "There is no segment named '%1!'."
** 17872, "This threshold is too close to one or more existing thresholds.
**	   Thresholds must be no closer than 128 pages to each other."
** 17874, "A threshold at %1! pages is logically impossible for
**	   segment '%2!'.  Choose a value between %3! and %4! pages."
** 17875, "Only the DBO of database '%1!' or a user with System Administrator
**	   (SA) authorization may add, delete, or modify thresholds in that
**	   database."
** 17904, "Segment '%1!' does not have a threshold at '%2!' pages."
** 18031, "This procedure can only affect thresholds in the current database.
**	   Say 'USE %1!', then run this procedure again."
** 18032, "You may not alter the free space or segment name of the
**	   log's last-chance threshold."
** 17289, "Set your curwrite to the hurdle of current database."
** 18084, "A threshold at %1! pages for segment '%2!' is too close to the 
**	   maximum size of the database. Because of this, the threshold will 
**	   not fire more than once per SQL server re-boot. Modify the value 
**	   using sp_modifythreshold to be between %3! and %4! pages."
*/

create procedure sp_modifythreshold
@dbname 	varchar(30),		/* this database	*/
@segname	varchar(30),		/* segment name		*/
@free_space	int,			/* threshold level	*/
@new_proc_name	varchar(255)=NULL,	/* threshold procedure	*/
@new_free_space	int = NULL,		/* new threshold level	*/
@new_segname	varchar(30) = NULL	/* new segment name	*/
as

declare	@segno	int,
	@segmap	int,
	@pagect	int,
	@status	int,
	@proxim	int,
	@newsegno int,
	@maxthpgct	int,
	@suid	smallint,
	@roles	varbinary(255),
	@proc	varchar(255),
	@msg	varchar(255)


/*
** If we are under a user defined xact, disallow this since we may 
** leave the dbtable's threshold cache out-of-sync if the end user 
** rollbacks its xact.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_modifythreshold"
	return (1)

end

set transaction isolation level 1
set chained off

/*
** Make sure we are in the right database
*/
if (@dbname != db_name())
begin
	/*
	** 18031, "You are in the wrong database.  Say 'USE %1!', then run
	**	   this procedure again."
	*/
	exec sp_getmessage 18031, @msg output
	print @msg, @dbname
	return (1)

end

/*
** Make sure our database is recent enough to contain Systhresholds
*/
if (select name from sysobjects
	where	name = 'systhresholds'
	  and	type = 'S')
   is NULL
begin
	/*
	** 17870, "Table '%1!' does not exist in database '%2!' -- cannot add
	**	  thresholds."
	*/
	exec sp_getmessage 17870, @msg output
	print @msg, "systhresholds", @dbname
	return (1)
end

/*
** Make sure the user (is the DBO) or (has "sa_role")
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
begin
	/*
	** 17875, "Only the DBO of database '%1!' or a user with System
	** Administrator (SA) authorization may add, delete, or modify
	** thresholds in that database."
	*/
	exec sp_getmessage 17875, @msg output
	print @msg, @dbname
	return (1)
end



/*
** Make sure the segment name is valid.
*/
select @segno = segment from syssegments where name = @segname
if @segno is NULL
begin
	/*
	** 17871, "There is no segment named '%1!'."
	*/
	exec sp_getmessage 17871, @msg output
	print @msg, @segname
	return (2)
end

/*
** Make sure the threshold exists
*/
select @proc = proc_name, @status = status
from	systhresholds
where	segment = @segno
  and	free_space = @free_space
if (@proc is null)
begin
	/*
	** 17904, "Segment '%1!' does not have a threshold at '%2!' pages."
	*/
	exec sp_getmessage 17904, @msg output
	print @msg, @segname, @free_space
	select	segment_name=@segname, free_space
	from	systhresholds
	where	segment = @segno

	return (1)
end

/*
** Establish values for new threshold items
*/
if (@new_free_space is NULL)
	select @new_free_space = @free_space
if (@new_segname is NULL)
	select @new_segname = @segname
if (@new_proc_name is NULL)
	select @new_proc_name = @proc
select @suid = suser_id()
select @roles = current_roles()

/*
** May not alter free space and segment name on the logsegment
** last-chance threshold
*/
if ((@segno = 2) and
    ((@status & 1) = 1) and
    ((@new_free_space != @free_space) or
     (@new_segname != @segname)))
begin
	/*
	** 18032, "You may not alter the free space or segment name of the
	**	   log's last-chance threshold."
	*/
	exec sp_getmessage 18032, @msg output
	print @msg

	return (1)
end

/*
** Make sure the threshold fits within the segment
*/
select @segmap = power(2, @segno)
select @pagect = sum(size) from master..sysusages
where	dbid = db_id()
  and	segmap & @segmap = @segmap
if (@new_free_space < 0) or (@new_free_space > @pagect)
begin
	/*
	** 17874, "A threshold at %1! pages is logically impossible for
	** segment '%2!'.  Choose a value between %3! and %4! pages."
	*/
	exec sp_getmessage 17874, @msg output
	print @msg, @new_free_space, @segname, 0, @pagect
	return (1)
end

/*
** Make sure there is no existing threshold too close to this new one
*/
select @proxim = (2 * @@thresh_hysteresis) - 1
if exists (select free_space from systhresholds
	where	segment = @segno
	  and	free_space between  (@new_free_space - @proxim)
				and (@new_free_space + @proxim)
	  and	free_space != @free_space)
begin
	/*
	** 17872, "This threshold is too close to one or more existing
	**	  thresholds.  Thresholds must be no closer than 128 pages
	**	  to each other."
	*/
	exec sp_getmessage 17872, @msg output
	print @msg
	select segment_name=@segname, free_space
	from systhresholds
	where	segment = @segno
	  and	free_space between (@free_space - @proxim)
				and (@free_space + @proxim)
	  and	free_space != @free_space

	return (1)
end

/*
** Make sure that the threshold is not too close to the maximum size of
** the database segment. If threshold value + @@thresh_hysteresis greater
** than maximum size of the database segment then threshold will fire only
** once.  Signal this condition to the user.
*/
select @maxthpgct = @pagect - @@thresh_hysteresis - 1
if (@pagect <= (@new_free_space + @@thresh_hysteresis))
begin
        /*
        ** 18084, "A threshold at %1! pages for segment '%2!' is too
        ** close to the maximum size of the database. Because of this,
        ** the threshold will not fire more than once per SQL server re-boot.
        ** Modify the value using sp_modifythreshold to be
        ** between %3! and %4! pages."
        */
        exec sp_getmessage 18084, @msg output
        print @msg, @new_free_space, @segname, 0, @maxthpgct

	/* This is not an error, so raise a message and continue.  */
end


/*
** Make sure that the new segment name provided by the user is a valid one.
*/
select @newsegno = segment from syssegments where name = @new_segname
if @newsegno is NULL
begin
	/*
	** 17871, "There is no segment named '%1!'."
	*/
	exec sp_getmessage 17871, @msg output
	print @msg, @new_segname
	return (2)
end

/*
** We do not validate the procedure name, since it might be in a different
** database or even in a remote server.  Thus, we have done all the tests
** we can.  Modify the threshold.
*/

/*
** 17906, "Dropping threshold for segment '%1!' at '%2!' pages."
*/
exec sp_getmessage 17906, @msg output
print @msg, @segname, @free_space


begin transaction modify_threshold

delete systhresholds
where	segment = @segno
  and	free_space = @free_space

if (@@error != 0)
begin
	rollback transaction
	/*
	** 17907, "Delete of systhresholds row failed."
	*/
	exec sp_getmessage 17907, @msg output
	print @msg
	return (1)
end

/*
** 17873, "Adding threshold for segment '%1!' at '%2!' pages."
*/
exec sp_getmessage 17873, @msg output
print @msg, @new_segname, @new_free_space




insert systhresholds values(@newsegno, @new_free_space, @status, 
			    @new_proc_name, @suid, @roles)


if (@@error != 0)
begin
	rollback transaction
	/*
	** 17877, "Insert of systhresholds row failed."
	*/
	exec sp_getmessage 17877, @msg output
	print @msg
	return (1)
end


/*
** Last, rebuild the database threshold table
*/
dbcc dbrepair(@dbname, "newthreshold")

if (@@error != 0)
begin
  rollback transaction
  /*
  ** 17878, "Rebuild of the database threshold table failed."
  */
	exec sp_getmessage 17878, @msg output
	print @msg
	return (1)
end

commit transaction

return (0)
go
exec sp_procxmode 'sp_modifythreshold', 'anymode'
go
grant execute on sp_modifythreshold to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_adduser')
begin
	drop procedure sp_adduser
end
go
print "Installing sp_adduser"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/adduser */

/*
** Messages for "sp_adduser"            17330
**
** 17240, "'" + @name_in_db + "' is not a valid name." 
** 17231, "No login with the specified name exists." 
** 17330, "A user with the same name already exists in the database."
** 17331, "User already has a login under a different name."
** 17332, "User already has alias access to the database."
** 17333, "No group with the specified name exists." 
** 17334, "All user ids have been assigned."
** 17335, "New user added."
*/

create procedure sp_adduser
@loginame varchar(30),			/* user's login name in syslogins */
@name_in_db varchar(30) = NULL,		/* user's name to add to current db */ 
@grpname varchar(30) = NULL		/* group to put new user in */
as

declare @suid int			/* user's system id */
declare @grpid int			/* group id of group to put user in */
declare @uid int			/* new user's id */
declare @msg varchar(250)
declare @returncode int



if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
	return(1)

/*
**  If no new user name is given, use the login name.
*/
if @name_in_db is NULL
	select @name_in_db = @loginame

/*
**  Check to see that the @name_in_db is valid.
*/
if valid_name(@name_in_db) = 0
begin
	/*
	** 17240, "'" + @name_in_db + "' is not a valid name." 
	*/
	exec sp_getmessage 17240, @msg output
	print @msg, @name_in_db
	return (1)
end

/*
**  The name guest is a special case.  If it doesn't have a login it
**  can still be a valid user.  We'll catch it here and special case it.
*/
if @loginame = "guest" and not exists
	(select name
		from master.dbo.syslogins
			where name = @loginame)
begin
	if exists (select *
			from sysusers
		   where name = @loginame)
	begin
		/*
		** 17330, "A user with the same name already exists in the database."
		*/
		exec sp_getmessage 17330, @msg output
		print @msg
		return (1)
	end

	/*
	**  Add the guest user and return.
	*/
	insert into sysusers (uid, suid, gid, name)
		values (2, -1, 0, "guest")

	return (0)
end

/*
**  Check to see that the user has a login name.
**  We'll also initialize @grpid to 0 while we're here.
*/
select @suid = suid, @grpid = 0
	from master.dbo.syslogins
where name = @loginame

if @suid is NULL
begin
	/*
	** 17231, "No login with the specified name exists." 
	*/
	exec sp_getmessage 17231, @msg output
	print @msg
	return (1)
end

/*
**  Now check to see if the user already exists in the database.
*/
if exists (select *
		   from sysusers
	   where name = @name_in_db)
begin
	/*
	** 17330, "A user with the same name already exists in the database."
	*/
	exec sp_getmessage 17330, @msg output
	print @msg
	return (1)
end

/*
**  See if the user already has an account under a different name.
**  That is, is the user's suid already in the sysusers table.
*/
if exists (select *
	   from sysusers
	   where suid = @suid)
begin
	/*
	** 17331, "User already has a login under a different name."
	*/
	exec sp_getmessage 17331, @msg output
	print @msg
	return (1)
end

/*
**  See if the user is known in the database already with an alias.
**  That is, does the user's suid appear in the sysalternates table.
*/
if exists (select *
	   from sysalternates
	   where suid = @suid)
begin
	/*
	** 17332, "User already has alias access to the database."
	*/
	exec sp_getmessage 17332, @msg output
	print @msg
	return (1)
end

/*
**  If a group name is given, check to see that it is valid.
**  User ids range from -16383 to +16383 and group ids are > 16383.
*/
if @grpname is not NULL
begin
	select @grpid = -1
	select @grpid = gid
		from sysusers
	where name = @grpname and (uid > 16383 or uid = 0)
		and not exists (select name from master.dbo.syssrvroles 
		where name = @grpname)


	if @grpid = -1
	begin
		/*
		** 17333, "No group with the specified name exists." 
		*/
		exec sp_getmessage 17333, @msg output
		print @msg
		return (1)
	end
end

/*
**  Add the user to the sysusers table.
**  Check to see if the special user 'guest' (uid = 2) has already
**  been added.  If not then the uid to use is 3, otherwise max(uid) + 1.
*/
select @uid = max(uid) + 1
	from sysusers
		where uid < 16384 and uid > 2

/* check if there's any more user id's available 
** The code in the following begin---end block is changed. Earlier we would
** raise an error when uids reached a positive limit of 16383. But now, we
** allocate uid's on the negative side as well . Therefore, error 17334
** will now be raised only when we have exhausted all uids between -16383
** and 16383.
** Note that uid of -1 is not used as it is declared as INVALID in the 
** Server code.
*/

if @uid >= 16384
begin
	select @uid  = min(uid) -1
		from sysusers

	/* As mentioned above, skip the value of -1 and start at -2. */
	if (@uid = -1)
		select @uid = -2

	else if (@uid <= -16384)
	begin
		/*
		** 17334, "All user ids have been assigned."
		*/
		exec sp_getmessage 17334, @msg output
		print @msg
		return (1)
	end
end

/*
**  This is the first regular user to be added so give them the first
**  number.
*/
if @uid is NULL
	select @uid = 3

insert into sysusers (uid, suid, gid, name)
	values (@uid, @suid, @grpid, @name_in_db)

/*
** 17335, "New user added."
*/
exec sp_getmessage 17335, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_adduser', 'anymode'
go
grant execute on sp_adduser to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addremotelogin')
begin
	drop procedure sp_addremotelogin
end
go
print "Installing sp_addremotelogin"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/addremotelogin */
/*
** Messages for "sp_addremotelogin"     17270
**
** 17260, "Can't run %1! from within a transaction." 
** 17270, "There is not a server named '%1!'."
** 17271, "'%1!' is the local server - remote login not applicable."               
** 17272, "There is already a default-name mapping of a remote login from remote server '%1!'."
** 17273, "New remote login created."
** 17274, "'%1!' isn't a local user -- remote login denied."
** 17275, "There is already a remote user named '%1!' for remote server '%2!'."
** 17276  "Usage: sp_addremotelogin remoteserver [, loginame [,remotename]]"
*/

create procedure sp_addremotelogin
@remoteserver	varchar(30),		/* name of remote server */
@loginame varchar(30) = NULL,		/* user's remote name */
@remotename varchar(30) = NULL		/* user's local user name */
as

declare	@msg	varchar(200)
declare @name   varchar(30)

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_addremotelogin"
	return (1)
end
else
begin
	set chained off
end
set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)


/*
**  Check that the server name is valid.
*/
if not exists (select *
			from master.dbo.sysservers
		where srvname = @remoteserver)
begin
	/*
	** 17270, "There is not a server named '%1!'."
	*/
	exec sp_getmessage 17270, @msg output
	print @msg, @remoteserver
	return (1)
end

/*
**  If it's the local server don't bother.
*/
if exists (select *
		from master.dbo.sysservers
			where srvname = @remoteserver
				and srvid = 0)
begin
	/*
	** 17271, "'%1!' is the local server - remote login not applicable."        
	*/
	exec sp_getmessage 17271, @msg output
	print @msg, @remoteserver
	return (1)
end

/*
**  There are three cases to handle.
**
**	1) if only @remoteserver is given then a entry is made in
**		sysremotelogins that means anyone that doesn't have
**		an exact of mapped match in sysremotelogins will use
**		their remotename as their local name and it will be looked
**		up in syslogins.
**
**	2) if @remotename is omitted then it means that anyone from the
**		remote server logging in that doesn't have a complete
**		match in sysremotelogins will be mapped to @loginame.
**
**	3) if @remotename and @loginame are given then it is a straight
**		remote login for sysremotelogins.
*/

/*
**  Case 1:  Only @remoteserver given.
*/
if @loginame is null and @remotename is null
begin
	/*
	**  Check that there is not already an entry for local mapping.
	*/
	if exists (select *
		from master.dbo.sysremotelogins l, master.dbo.sysservers s
			where l.remoteserverid = s.srvid
				and s.srvname = @remoteserver
				and l.remoteusername is null)
	begin
		/*
		** 17272, "There is already a default-name mapping of a remote login from remote server '%1!'."
		*/
		exec sp_getmessage 17272, @msg output
		print @msg, @remoteserver
		return (1)
	end

	/*
	**  Add the entry.
	*/
	insert into master.dbo.sysremotelogins 
		(remoteserverid, remoteusername, suid, status)
	select srvid, null, -1, 0
		from master.dbo.sysservers
			where srvname = @remoteserver
	/*
	** 17273, "New remote login created."
	*/
	exec sp_getmessage 17273, @msg output
	print @msg
	return (0)

end

/*
**  Check that the @loginame is valid.  These is needed for both
**  case 2 and 3.
*/
if not exists (select *
		from master.dbo.syslogins
			where name = @loginame)
begin
	/*
	** 17274, "'%1!' isn't a local user -- remote login denied."
	*/
	exec sp_getmessage 17274, @msg output
	print @msg, @loginame
	return (1)
end

/*
**  Check to make sure that there is not already a @remotename for 
**  the @remoteserver.
*/
if exists (select *
		from master.dbo.sysremotelogins l, master.dbo.sysservers s
			where l.remoteserverid = s.srvid
				and s.srvname = @remoteserver
				and l.remoteusername = @remotename)
begin
	/*
	** 17275, "There is already a remote user named '%1!' for remote server '%2!'."
	*/
	select @name = isnull(@remotename, "NULL")
	exec sp_getmessage 17275, @msg output
	print @msg, @name, @remoteserver

	return (1)
end
	

/*
**  Case 2: We want to make an entry into sysremotelogins that will map
**	any non-exact matches to a particular local user.
*/
if @remotename is null
begin
	/*
	**  Check that there is not already an entry for local mapping.
	*/
	if exists (select *
		from master.dbo.sysremotelogins l, master.dbo.sysservers s
			where l.remoteserverid = s.srvid
				and s.srvname = @remoteserver
				and l.remoteusername is null)
	begin
		/*
		** 17272, "There is already a default-name mapping of a remote login from remote server '%1!'."
		*/
		exec sp_getmessage 17272, @msg output
		print @msg, @remoteserver
		return (1)
	end

	/*
	**  Go ahead and make the entry.
	*/
	insert into master.dbo.sysremotelogins
		(remoteserverid, remoteusername, suid, status)
	select srvid, null, suser_id(@loginame), 0
		from master.dbo.sysservers
				where srvname = @remoteserver

	/*
	** 17273, "New remote login created."
	*/
	exec sp_getmessage 17273, @msg output
	print @msg
	return (0)
end

/*
**  Case 3:  All the parameters have been supplied.  All we need to check
**	is that the entry isn't already in sysremotelogins.
**	We've verified the @remoteserver and @loginame above.
*/
if @loginame is not null and @remotename is not null
begin
	/*
	**  Make sure that the @loginame and @remotename are a
	**  unique combination.
	*/
	if exists (select *
		from master.dbo.sysremotelogins l, master.dbo.sysservers s
			where l.remoteusername = @remotename
				and l.remoteserverid = s.srvid
				and s.srvname = @remoteserver
				and l.suid = suser_id(@loginame))
	begin
		/*
		** 17275, "There is already a remote user named '%1!' for remote server '%2!'."
		*/
		exec sp_getmessage 17275, @msg output
		print @msg, @remotename, @remoteserver
		return (1)
	end

	/*
	**  Go ahead the do the insert.
	*/
	insert into master.dbo.sysremotelogins
		(remoteserverid, remoteusername, suid, status)
	select srvid, @remotename, suser_id(@loginame), 0
		from master.dbo.sysservers
			where srvname = @remoteserver
	/*
	** 17273, "New remote login created."
	*/
	exec sp_getmessage 17273, @msg output
	print @msg
	return (0)
end

/*
**  We got here because the syntax was incorrect.
*/
exec sp_getmessage 17276, @msg output
print @msg
return (1)
go
exec sp_procxmode 'sp_addremotelogin', 'anymode'
go
grant execute on sp_addremotelogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addsegment')
begin
	drop procedure sp_addsegment
end
go
print "Installing sp_addsegment"
go

/* Sccsid = "@(#) generic/sproc/src/%M% %I% %G%" */
/*	4.1	1.1	06/14/90	sproc/src/addsegment */
/*
** Messages for "sp_addsegment"         17280
**
** 17260, "Can't run %1! from within a transaction." 
** 17280, "No such device exists -- run sp_helpdb to list the
** 	  devices for the current database."
** 17281, "The specified device is not used by the database."
** 17282, "The specified device is not a database device."
** 17283, "'%1!' is reserved exclusively as a log device."
** 17284, "'%1!' is not a valid identifier."
** 17285, "There is already a segment named '%1!'."
** 17286, "The maximum number of segments for the current database are already defined."
** 17287, "Segment created."
** 17288, "You must execute this procedure from the database 
** 	  in which you wish to add a segment.  Please execute 
**	  'use %1!' and try again."
** 17590, "The specified database does not exist." 
** 17289, "Set your curwrite to the hurdle of current database."
** 18072, "Setting curwrite to data_low for updating syssegments failed."
*/
create procedure sp_addsegment
@segname	varchar(30),	/* segment name */
@dbname		varchar(30),	/* database name */
@devname	varchar(30)	/* device name to put segment on */
as

declare @dbuid	smallint	/* id of the owner of the database */
declare @segbit	int		/* this is the bit to turn on in sysusages */
declare	@msg	char(250)
declare @returncode int
declare @name varchar(30)
declare @procval int
select @procval = 0
/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	select @name = "sp_addsegment"
	exec sp_getmessage 17260, @msg output
	print @msg, @name
	return (1)
end
else
begin
	set chained off
end
set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  if user  had SA role he would be the dbo hence check only
**  whether user is DBO.
**  Call proc_role() with the required SA role.
*/
if (user_id() = 1)
begin
	/* If user has sa role audit this as a successful sa
	** command execution.
	** If in the future we add new role with "sa" as 
	** substring or allow roles to be added the following could
	** result in an incorrect (extra) audit record being sent.
	*/
	if charindex("sa_role",show_role()) > 0
		select @procval = proc_role("sa_role")
end
else 
begin
	/* user_id() is not DBO hence user does not have SA role
	** audit this as a failed sa command execution.
	*/
	select @procval = proc_role("sa_role")
	return (1)
end

/*
**  Make ure the database exists
*/
if not exists ( select * from master.dbo.sysdatabases
		where name = @dbname )
begin
	/* 17590, "The specified database does not exist." */
	exec sp_getmessage 17590, @msg out
	print @msg
	return (1)
end

/*
**  Make sure that we are in the database specified
**  by @dbname. 
*/
if @dbname != db_name()
begin
	/* 
	** 17288, "You must execute this procedure from the database 
	** 	  in which you wish to add a segment.  Please execute 
	**	  'use %1!' and try again."
	*/
	exec sp_getmessage 17288, @msg out
	print @msg, @dbname
	return (1)
end

/*
**  See if the device exists.
*/
if not exists (select *
		from master.dbo.sysdevices
			where name like @devname)
begin
	/*
	** 17280, "No such device exists -- run sp_helpdb to list the
	** 	  devices for the current database."
	*/
	exec sp_getmessage 17280, @msg output
	print @msg
	return (1)
end

/*
**  Check to see if the device is marked as a log device.
**  If so, print error.
*/
if exists (select *
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = db_id(@dbname)
				and segmap = 4)
begin
	/*
	** 17283, "'%1!' is reserved exclusively as a log device."
	*/
	exec sp_getmessage 17283, @msg output
	print @msg, @devname
	return (1)
end

/*
**  Now see if the @devname is a proper database device
*/
if not exists (select *
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = db_id(@dbname)
				and d.cntrltype = 0)
begin
	/*
	** 17282, "The specified device is not a database device."
	*/
	exec sp_getmessage 17282, @msg output
	print @msg
	return (1)
end

/*
**  Now see if the @dbname uses the @devname
*/
if not exists (select *
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = db_id(@dbname))
begin
	/*
	** 17281, "The specified device is not used by the database."
	*/
	exec sp_getmessage 17281, @msg output
	print @msg
	return (1)
end

/*
** Check for valid identifier.
*/
if valid_name(@segname) = 0
begin
	/*
	** 17284, "'%1!' is not a valid identifier."
	*/
	exec sp_getmessage 17284, @msg output
	print @msg, @segname
	return (1)
end

/*
**  Now go ahead and define the new segment and add it to the segmap
**  of sysusages.
**  NOTE: Don't update master..sysusages and syssegments as a xact since
**  	it could cause problems for recovery.
*/

/*
**  Check that @segname doesn't already exist.
*/
if exists (select *
		from syssegments holdlock
			where name = @segname)
begin
	/*
	** 17285, "There is already a segment named '%1!'."
	*/
	exec sp_getmessage 17285, @msg output
	print @msg, @segname
	return (1)
end

/*
**  Figure out the next segment number to use.
**  Segment number may be 0-31.
*/
select @segbit = 3
while @segbit < 32
begin
	/*
	**  Did we find one?
	*/
	if exists (select *
			from syssegments
				where segment = @segbit)
	begin
		select @segbit = @segbit + 1
	end

	/*
	**  We found an opening so break out.
	*/
	else break

end

if @segbit >= 32
begin
	/*
	** 17286, "The maximum number of segments for the current database are already defined."
	*/
	exec sp_getmessage 17286, @msg output
	print @msg
	return (1)
end



/*
**  Add the new segment.
*/
insert into syssegments (segment, name, status)
	values (@segbit, @segname, 0)



/*
**  Now set the segments on @devname sysusages.
*/
if (@segbit < 31)
	select @segbit = power(2, @segbit)
else
	/*
	**  Since this is segment 31, power(2, 31) will overflow
	**  since segmap is an int.  We'll grab the machine-dependent
	**  bit mask from spt_values to set the right bit.
	*/
	select @segbit = low
		from master.dbo.spt_values
			where type = "E"
				and number = 2
update master.dbo.sysusages
	set segmap = segmap | @segbit
		from master.dbo.sysusages u,
			master.dbo.sysdevices d
		where d.name = @devname
			and u.vstart between d.low and d.high
			and u.dbid = db_id( @dbname)

/*
**  Now we need to activate the new segment map.
*/
dbcc dbrepair (@dbname, remap)
/*
** 17287, "Segment created."
*/
exec sp_getmessage 17287, @msg output
print @msg
return (0)
go
exec sp_procxmode 'sp_addsegment', 'anymode'
go
grant execute on sp_addsegment to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addserver')
begin
	drop procedure sp_addserver
end
go
print "Installing sp_addserver"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/addserver */

/*
** Messages for "sp_addserver"          17290
**
** 17260, "Can't run %1! from within a transaction." 
** 17240, "'" + @lname + "' is not a valid name." 
** 17290, "There is already a server named '%1!', physical name '%2!'."
** 17291, "Usage: sp_addserver servername [, 'local | NULL'] [, physical_name]"
** 17292, "There is already a local server."
** 17293, "Server added."
** 17294, "Changing physical name of server '%1!' from '%2!' to '%3!'"
** 17295, "Adding server '%1!', physical name '%2!'"
*/

create procedure sp_addserver
@lname	varchar(30),		/* server logical name */
@local	varchar(10) = NULL,	/* local server */
@pname	varchar(30) = NULL	/* server physical name */

as

declare	@msg	 varchar(250),
	@netname varchar(30)

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_addserver"
	return (1)
end
else
begin
	set chained off
end
set transaction isolation level 1

/* check if user has sso role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sso_role") = 0)
	return (1)


/*
**  Check to see that the @lname is valid.
*/
if valid_name(@lname) = 0
begin
	/*
	** 17240, "'" + @lname + "' is not a valid name." 
	*/
	exec sp_getmessage 17240, @msg output
	print @msg, @lname
	return (1)
end

/*
**  Check to see that the @pname is valid.
*/
if (@pname is NULL)
	select @pname = @lname
else
if valid_name(@pname) = 0
begin
	/*
	** 17240, "'" + @pname + "' is not a valid name." 
	*/
	exec sp_getmessage 17240, @msg output
	print @msg, @pname
	return (1)
end

/*
**  Server names must be unique so check.  If a server already exists with
**  this logical _and_ physical name, the server already exists, so there's
**  no work to do.  However, if the logical name exists but the physical
**  names differ, this will be an update to the table to change the physical
**  name.
*/
if exists (select *
		from master.dbo.sysservers
			where srvname = @lname)
begin
	 select @netname = srvnetname
		from master.dbo.sysservers
			where srvname = @lname

	/*
	** 17290, "There is already a server named '%1!', physical name '%2!'."
	*/
	if (@netname = @pname)
	begin
		exec sp_getmessage 17290, @msg output
		print @msg, @lname, @pname
		return (1)
	end

	/*
	** 17294, "Changing physical name of server '%1!' from '%2!' to '%3!'"
	*/
	exec sp_getmessage 17294, @msg output
	print @msg, @lname, @netname, @pname

	update master.dbo.sysservers
	set srvnetname = @pname
	where srvname = @lname

	return (@@error)
end


/*
**  If this is not the local server, then its srvid = max(srvid) + 1.
*/
if @local is null
begin	

	/*
	** 17295, "Adding server '%1!', physical name '%2!'"
	*/
	exec sp_getmessage 17295, @msg output
	print @msg, @lname, @pname



	insert into master.dbo.sysservers (srvid, srvstatus, srvname, srvnetname)
			select isnull(max(srvid), 0) + 1, 0, @lname, @pname
				from master.dbo.sysservers

end

/*
**  If @local = "local" then this is the local server and it's
**  srvid = 0.
*/
else
begin
	if lower(@local) != "local"
	begin
		/*
		** 17291, "Usage: sp_addserver servername [, 'local | NULL'],
		**	   [, physical_name]"
		*/
		exec sp_getmessage 17291, @msg output
		print @msg
		return (1)
	end

	if exists (select *
			from master.dbo.sysservers
				where srvid = 0)
	begin
		/*
		** 17292, "There is already a local server."
		*/
		exec sp_getmessage 17292, @msg output
		print @msg
		return (1)
	end

	/*
	** 17295, "Adding server '%1!', physical name '%2!'"
	*/
	exec sp_getmessage 17295, @msg output
	print @msg, @lname, @pname



	insert into master.dbo.sysservers (srvid, srvstatus, srvname, srvnetname)
			values (0, 0, @lname, @pname)

end

/*
** 17293, "Server added."
*/
exec sp_getmessage 17293, @msg output
print @msg
return (0)
go
exec sp_procxmode 'sp_addserver', 'anymode'
go
grant execute on sp_addserver to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addlanguage')
begin
	drop procedure sp_addlanguage
end
go
print "Installing sp_addlanguage"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/addlanguage */

/*
** Messages for "sp_addlanguage"        17250
**
** 17250, "'%1!' already exists in Syslanguages."
** 17251, "'%1!' is not a valid date order."
** 17252, "'%1!' is not a valid first day."
** 17253, "'%1!' alias already exists in Syslanguages."
** 17254, "Language not inserted."
** 17255, "New language inserted."
*/

create procedure sp_addlanguage 
@language varchar(30),
@alias varchar(30) = NULL,
@months varchar(251),
@shortmons varchar(119),
@days varchar(216),
@datefmt char(3),
@datefirst tinyint
as

declare @msg varchar(250)
declare @nextlangid smallint
declare @returncode	int 
declare @convdate char(3)


/*
** NOTE:
** We should check here to see if we're in a transaction, and return
** with a 17260 error ("Can't run %1! from within a transaction.") if
** we are in a transaction.  However, the langinstall utility currently
** calls sp_addlanguage from within a transaction.  Until this behavior
** is changed we'll allow ourselves to be called from within a xact.
*/

/* 
** check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*  Check to see if the language exists. */
select @returncode = 0
execute @returncode = sp_validlang @language
if @returncode = 0
begin
	/*
	**  17250, "'%1!' already exists in Syslanguages."
	*/
	exec sp_getmessage 17250, @msg output
	print @msg, @language
	return 1
end

/* Check to see that the list of full month names is valid. */
execute @returncode = sp_chklangparam @months, "full month", 12, 20
if @returncode != 0
	return 1

/* Check to see that the list of short month names is valid. */
execute @returncode = sp_chklangparam @shortmons, "short month", 12, 9
if @returncode != 0
	return 1

/* Check to see that the list of day names is valid. */
execute @returncode = sp_chklangparam @days, "day", 7, 30
if @returncode != 0
	return 1

/* Check to see that the @datefmt is valid. */
if (@datefmt != 'mdy' and @datefmt != 'dmy' and @datefmt != 'ymd' and @datefmt != 'ydm'
	and @datefmt != 'myd' and @datefmt != 'dym')
begin
	/*
	** 17251, "'%1!' is not a valid date order."
	*/
	exec sp_getmessage 17251, @msg output
	print @msg, @datefmt
	return 1
end

/*
**  Check to see that the @datefirst is valid.
*/
if (@datefirst < 1 or @datefirst > 7)
begin
	/*
	** 17252, "'%1!' is not a valid first day."
	*/
	select @convdate = convert(char(3), @datefirst)
	exec sp_getmessage 17252, @msg output
	print @msg, @convdate
	return 1
end

/*
**  If the user didn't specify the alias name, the alias name is same as 
**  the official name.
*/
if @alias is null
begin
	select @alias =  @language
end

/*  Check to see if the alias exists. */
select @returncode = 0
execute @returncode = sp_validaltlang @alias
if @returncode = 0
begin
	/*
	** 17253, "'%1!' alias already exists in Syslanguages."
	*/
	exec sp_getmessage 17253, @msg output
	print @msg, @alias
	return 1
end

if @language = 'us_english'
begin
	/*  The language id of us_english is 0. */
	insert master.dbo.syslanguages (langid, dateformat, datefirst, upgrade, 
		name, alias, months, shortmonths, days)
	select 0, @datefmt, @datefirst, 0, 
		@language, @alias, @months, @shortmons, @days
end
else
begin

	if (select max(langid) from master.dbo.syslanguages) is null
	begin
		select @nextlangid = 1
	end
	else
	begin
		select @nextlangid = (select max(langid)+1 
		from master.dbo.syslanguages)
	end

	insert master.dbo.syslanguages (langid, dateformat, datefirst, upgrade, 
		name, alias, months, shortmonths, days)
	select @nextlangid, @datefmt, @datefirst, 0, 
		@language, @alias, @months, @shortmons, @days
end


/* If the insert failed, say so. */
if @@error != 0
begin
	/*
	** 17254, "Language not inserted."
	*/
	exec sp_getmessage 17254, @msg output
	print @msg
	return
end

/*
** 17255, "New language inserted."
*/
exec sp_getmessage 17255, @msg output
print @msg
    
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_defaultlanguage')
begin
	drop procedure sp_defaultlanguage
end
go
print "Installing sp_defaultlanguage"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_defaultlanguage"    17450
**
** 17201, "'%1!' is not a valid official language name." **
** 17260, "Cant run %1! from within a transaction."
** 17451, "This user does not exist.  Run sp_addlogin to add this user in."
** 17452, "%1!'s default language has been changed to %2!."
** 17453, "Error in changing the default language."
*/

create procedure sp_defaultlanguage
@loginame varchar(30),			/* login name of the user */
@language varchar(30) = NULL		/* default language for the new user */
as

declare @msg varchar(250)
declare @returncode int

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_defaultlanguage"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* 
**  Check to see that the @language is valid.
*/
if @language is not null
begin
	select @returncode = 0
	execute @returncode = sp_validlang @language
	if @returncode != 0
	begin
		if @language != "us_english"
		begin
			/*
			** 17201, "'%1!' is not a valid official language name." **
			*/
			exec sp_getmessage 17201, @msg output
			print @msg, @language
			return @returncode
		end
	end
end

/*
**  Make sure the login already exist.
*/
if not exists (select *
	from master.dbo.syslogins
	where name = @loginame)
begin
	/*
	** 17451, "This user does not exist.  Run sp_addlogin to add this user in."
	*/
	exec sp_getmessage 17451, @msg output
	print @msg
	return 1
end

/*
**  Only the Account Owner or
**  Accounts with SA role can execute it.
*/
if ((suser_id() != suser_id(@loginame)) and (proc_role("sa_role") != 1))
	return(1)

/*
**  Set the default language for this user.
*/
update master.dbo.syslogins 
	set language = @language
 	where name = @loginame

if @@rowcount = 1
begin
	/*
	** 17452, "%1!'s default language has been changed to %2!."
	*/
	exec sp_getmessage 17452, @msg output
	print @msg, @loginame, @language
	select @returncode = 0
end
else
begin
	/*
	** 17453, "Error in changing the default language."
	*/
	exec sp_getmessage 17453, @msg output
	print @msg
	select @returncode = 1
end
return (@returncode)

go
exec sp_procxmode 'sp_defaultlanguage', 'anymode'
go
grant execute on sp_defaultlanguage to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helplanguage')
begin
	drop procedure sp_helplanguage
end
go
print "Installing sp_helplanguage"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */
/*
** Messages for "sp_helplanguage"       17670
**
** 17201, "'%1!' is not an official language name from Syslanguages."
** 17670, "No alternate languages are available."
** 17671, "us_english is always available, even though it is not in
**	master.dbo.syslanguages."
*/
create procedure sp_helplanguage 
@language varchar(30) = NULL
as

declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* Print all languages if the user didn't give the language name. */
if @language is null
begin
	if exists (select * from master.dbo.syslanguages)
		select * from master.dbo.syslanguages
	else
	begin
		/* 17670, "No alternate languages are available." */
		exec sp_getmessage 17670, @msg out
		print @msg
	end

	/* Find out whether us_english is there or not. */
	if not exists (select * from master.dbo.syslanguages   
			where name = 'us_english') 
	begin
		/* 
		** 17671, "us_english is always available, even though it is not in
		** 	master.dbo.syslanguages." 
		*/
		exec sp_getmessage 17671, @msg out
		print @msg
	end

	return 0
end

/*  Report information on this language. */
if exists (select * from master.dbo.syslanguages   
                where name = @language) 
begin
        select * from master.dbo.syslanguages 
                where name = @language
        return 0
end 

if exists (select * from master.dbo.syslanguages
		where alias = @language)
begin
	select * from master.dbo.syslanguages 
		where alias = @language
	return 0
end

/* Couldn't find this language. */
if @language = 'us_english'
begin
	/* 
	** 17671, "us_english is always available, even though it is not in
	** 	master.dbo.syslanguages." 
	*/
	exec sp_getmessage 17671, @msg out
	print @msg
	return 0
end
else
begin
	/* 17201, "'%1!' is not an official language name from Syslanguages." */
	exec sp_getmessage 17201, @msg out
	print @msg, @language
	return 1
end
go
exec sp_procxmode 'sp_helplanguage', 'anymode'
go
grant execute on sp_helplanguage to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_droplanguage')
begin
	drop procedure sp_droplanguage
end
go
print "Installing sp_droplanguage"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_droplanguage"       17505
**
** 17201, "'%1!' is not an official language name from Syslanguages." 
** 17260, "Can't run %1! from within a transaction."
** 17505, "Can't drop '%1!' because there are associated entries in master.dbo.sysmessages.  Run sp_droplanguage with the 'dropmessages' flag."
** 17506, "The only legal value for @dropmessages is 'dropmessages'."
** 17507, "Language deleted."
*/

create procedure sp_droplanguage 
@language varchar(30),
@dropmessages varchar(30) = NULL
as

declare @msg varchar(250)
declare @langid smallint
declare @dropmsgs int

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/* 17260, "Can't run %1! from within a transaction." */
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_locklogin"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*  Check to see if the language exists. */
declare @returncode	int 
select @returncode = 0
execute @returncode = sp_validlang @language
if @returncode != 0
begin
	/*
	** 17201, "'%1!' is not an official language name from Syslanguages." 
	*/
	exec sp_getmessage 17201, @msg output
	print @msg, @language 
	return 1
end

/* Get language id from syslanguages. */
select @langid = (select langid 
			from master.dbo.syslanguages 
				where name = @language)

/*  Check to see if "dropmessages" is requested. */
select @dropmsgs = 0
if @dropmessages is null
begin
	if exists (select * from master.dbo.sysmessages 
			where langid = @langid)
	begin
		/* 
		**  Cannot drop a language if the language has associated
		**  entries in the master.dbo.sysmessages.
		*/

		/*
		** 17505, "Can't drop '%1!' because there are associated entries in master.dbo.sysmessages.  Run sp_droplanguage with the 'dropmessages' flag."
		*/
		exec sp_getmessage 17505, @msg output
		print @msg, @language
		return 1
	end
end
else
begin
	if @dropmessages != "dropmessages"
	begin
		/*
		** 17506, "The only legal value for @dropmessages is 'dropmessages'."
		*/
		exec sp_getmessage 17506, @msg output
		print @msg
		return 1
	end

	select @dropmsgs = 1
end

/* 
**  Drop the language and delete messages from Sysmessages if there is any.
*/
if @dropmsgs = 1
begin
	delete master.dbo.sysmessages
		where langid = @langid
end

delete master.dbo.syslanguages 
	where langid = @langid

/*
** 17507, "Language deleted."
*/
exec sp_getmessage 17507, @msg output
print @msg
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setlangalias')
begin
	drop procedure sp_setlangalias
end
go
print "Installing sp_setlangalias"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */

/*
** Messages for "sp_setlangalias"       17810
**
** 17201, "'%1!' is not an official language name from Syslanguages."
** 17260, "Can't run %1! from within a transaction."
** 17253, "'%1!' alias already exists in Syslanguages."
** 17810, "Language alias not changed."
** 17811, "Language alias reset."
*/

create procedure sp_setlangalias 
@language varchar(30),
@alias varchar(30)
as

declare @msg varchar(250)

declare @returncode	int 


/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_setlangalias"
        return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*  Check to see if the language exists. */
select @returncode = 0
execute @returncode = sp_validlang @language
if @returncode != 0
begin
	/*
	** 17201, "'%1!' is not an official language name from Syslanguages."
	*/
	exec sp_getmessage 17201, @msg output
	print @msg, @language
	return 1
end

/*  Check to see if the alias exists. */
select @returncode = 0
execute @returncode = sp_validaltlang @alias
if @returncode = 0
begin
	/*
	** 17253, "'%1!' alias already exists in Syslanguages."
	*/
	exec sp_getmessage 17253, @msg output
	print @msg, @alias
	return 1
end

/* Reset the alternate language name. */
update master.dbo.syslanguages 
	set alias = @alias
		where name = @language

/* If the update failed, say so. */
	if @@error != 0
begin
	/*
	** 17810, "Language alias not changed."
	*/
	exec sp_getmessage 17810, @msg output
	print @msg
	return
end

/*
** 17811, "Language alias reset."
*/
exec sp_getmessage 17811, @msg output
print @msg
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindefault')
begin
	drop procedure sp_bindefault
end
go
print "Installing sp_bindefault"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/bindefault */

/*
** Messages for "sp_bindefault"         17340
**
** 17340, "Default and table or usertype must be in 'current' database."
** 17341, "Usage: bindefault defaultname, objectname [, 'futureonly']"
** 17342, "No such default exists.  You must create the default first."
** 17343, "You can't bind a default to a timestamp datatype column."
** 17344, "You do not own a column of that name."
** 17345, "Default bound to column."
** 17346, "You do not own a datatype of that name."
** 17347, "Default bound to datatype."
** 17348, "The new default has been bound to columns(s) of the specified user datatype."
** 17349, "You cannot bind a declared default. The default must be created using create default."
** 17753, "The column already has a default. Bind disallowed."
*/ 

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_bindefault
@defname varchar(92),			/* name of the default */
@objname varchar(61),			/* table or usertype name */
@futureonly varchar(15) = NULL		/* flag to indicate extent of binding */
as

declare @futurevalue varchar(15)	/* the value of @futureonly that causes
					** the binding to be limited */
declare @msg   varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

select @futurevalue = "futureonly"	/* initialize @futurevalue */

/*
**  When a default or rule is bound to a user-defined datatype, it is also
**  bound, by default, to any columns of the user datatype that are currently
**  using the existing default or rule as their default or rule.  This default
**  action may be overridden by setting @futureonly = @futurevalue when the
**  procedure is invoked.  In this case existing columns with the user
**  datatype won't have their existing default or rule changed.
*/

/*
**  Check to see that the object names are local to the current database.
*/
if (@objname like "%.%.%")
   or
   (@defname like "%.%.%" and
	substring(@defname, 1, charindex(".", @defname) - 1) != db_name())
begin
	/*
	** 17340, "Default and table or usertype must be in 'current' database."
	*/
	exec sp_getmessage 17340, @msg output
	print @msg
	return (1)
end

/*
**  Check that the @futureonly argument, if supplied, is correct.
*/
if (@futureonly is not null)
begin
	if (@futureonly != @futurevalue)
	begin
		/*
		** 17341, "Usage: bindefault defaultname, objectname [, 'futureonly']"
		*/
		exec sp_getmessage 17341, @msg output
		print @msg
		return (1)
	end
end

/*
**  Check to see that the default exists and get it's id.
*/
if not exists (select id
		from sysobjects
	where id = object_id(@defname)
		and sysstat & 7 = 6)		/* default object */
begin
	/*
	** 17342, "No such default exists.  You must create the default first."
	*/
	exec sp_getmessage 17342, @msg output
	print @msg
	return (1)
end

/*
** Check to see that the default is not of declared type
*/

if exists (select * from sysprocedures
		where id = object_id(@defname)
		and sequence = 0
		and status & 4096 = 4096)
begin
	/*
	** 17349, "You cannot bind a declared default. The default must be created \
using create default."
	*/
	exec sp_getmessage 17349, @msg output
	print @msg
	return (1)
end

/*
**  If @objname is of the form tab.col then we are binding to a column.
**  Otherwise its a datatype.  In the column case, we need to extract
**  and verify the table and column names and make sure the user owns
**  the table that is getting the default bound.
*/
if @objname like "%.%"
begin
	declare @tabname varchar(30)		/* name of table */
	declare @colname varchar(30)		/* name of column */

	/*
	**  Get the table name out.
	*/
	select @tabname = substring(@objname, 1, charindex(".", @objname) - 1)
	select @colname = substring(@objname, charindex(".", @objname) + 1, 61)

	/*
	**  If the column type is timestamp, disallow the bind.
	**  Defaults can't be bound to timestamp columns.
	*/
	if exists (select *
			from sysobjects o, syscolumns c
		where c.id = object_id(@tabname)
			and c.name = @colname
			and c.name = @colname
			and o.id = object_id(@tabname)
			and o.sysstat & 7 = 3
			and c.usertype = 80)
	begin
		/*
		** 17343, "You can't bind a default to a timestamp datatype column."
		*/
		exec sp_getmessage 17343, @msg output
		print @msg
		return (1)
	end

	/*
	** If the column already has a default, then disallow the bind
	*/
	if exists (select * from syscolumns c
			where c.id = object_id(@tabname)
			and c.name = @colname
			and c.cdefault != 0)
	begin
		/*
		** 17753, "The column already has a default. Bind disallowed."
		*/
		exec sp_getmessage 17753, @msg output
		print @msg
		return (1)
	end

	update syscolumns
		set cdefault = object_id(@defname)
			from syscolumns, sysobjects
		where syscolumns.id = object_id(@tabname)
			and syscolumns.name = @colname
			and sysobjects.id = object_id(@tabname)
			and uid = user_id()
			and sysobjects.sysstat & 7 = 3      /* user table */

	/*
	**  Did the bind happen?
	*/
	if @@rowcount != 1
	begin
		/*
		** 17344, "You do not own a column of that name."
		*/
		exec sp_getmessage 17344, @msg output
		print @msg
		return (1)
	end

	/*
	**  Since binding a default is a schema change, update schema count
	**  for the object in the sysobjects table.
	*/
	update sysobjects
		set schemacnt = schemacnt + 1
			from sysobjects
				where id = object_id(@tabname)
					and uid = user_id()
					and schema_inc(object_id(@tabname)) is NULL

	/*
	** 17345, "Default bound to column."
	*/
	exec sp_getmessage 17345, @msg output
	print @msg

end
else
begin
	/*
	**  We're binding to a user type.  In this case, the @objname
	**  is really the name of the user datatype.
	**  When we bind to a user type, any existing columns get changed
	**  to the new binding unless their current binding is not equal
	**  to the current binding for the usertype or if they set the
	**  @futureonly parameter to @futurevalue.
	*/
	/*
	**  Get the current default for the datatype.
	*/
	if not exists (select tdefault
			from systypes
			where name = @objname
				and uid = user_id() and usertype > 100)
	begin
		/*
		** 17346, "You do not own a datatype of that name."
		*/
		exec sp_getmessage 17346, @msg output
		print @msg
		return (1)
	end

	update systypes
		set tdefault = object_id(@defname)
			from systypes
		where name = @objname
			and uid = user_id()
			and usertype > 100


	/*
	** 17347, "Default bound to datatype."
	*/
	exec sp_getmessage 17347, @msg output
	print @msg

	/*
	**  Now see if there are any columns with the usertype that
	**  need the new binding.
	*/
	if isnull(@futureonly, "") != @futurevalue
		and exists (select *
			from syscolumns, systypes
				where syscolumns.usertype = systypes.usertype
					and systypes.name = @objname
					and systypes.usertype > 100
					and systypes.uid = user_id())
	begin
		/*
		**  Update the table schema to indicate that something
		**  has changed in the table's schema.
		*/
		update sysobjects
			set schemacnt = schemacnt + 1
				from sysobjects, syscolumns, systypes
			where sysobjects.id = syscolumns.id
				and syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()
				and sysobjects.id in
					(select s.id from sysobjects s
					where schema_inc(s.id) is NULL)

		/*
		**  Update syscolumns with new binding.
		*/
		update syscolumns
			set cdefault = systypes.tdefault
				from syscolumns, systypes
			where syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()


		/*
		** 17348, "The new default has been bound to columns(s) of the specified user datatype."
		*/
		exec sp_getmessage 17348, @msg output
		print @msg

	end
end

return (0)
go
exec sp_procxmode 'sp_bindefault', 'anymode'
go
grant execute on sp_bindefault to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindrule')
begin
	drop procedure sp_bindrule
end
go
print "Installing sp_bindrule"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/bindrule */

/*
** Messages for "sp_bindrule"           17350
**
** 17344, "You do not own a column of that name." 
** 17346, "You do not own a datatype of that name." 
** 17350, "Rule and table or usertype must be in 'current' database."
** 17351, "Usage: bindrule rulename, objectname [, 'futureonly']"
** 17352, "No such rule exists.  You must create the rule first."
** 17353, "You can't bind a rule to a text, image, or timestamp datatype column."
** 17354, "Rule bound to table column."
** 17355, "You can't bind a rule to a text, image, or timestamp datatype."
** 17356, "Rule bound to datatype."
** 17357, "The new rule has been bound to column(s) of the specified user datatype."
** 17358, "You cannot bind a declared constraint. The rule must be created using create rule."
*/


/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_bindrule
@rulename varchar(92),			/* name of the rule */
@objname varchar(61),			/* table or usertype name */
@futureonly varchar(15) = NULL		/* column name */
as

declare @futurevalue varchar(15)	/* the value of @futureonly that causes
					** the binding to be limited */
declare @status tinyint			/* column status */
declare @colid tinyint			/* column id */
declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

select @futurevalue = "futureonly"	/* initialize @futurevalue */

/*
**  When a default or rule is bound to a user-defined datatype, it is also
**  bound, by default, to any columns of the user datatype that are currently
**  using the existing default or rule as their default or rule.  This default
**  action may be overridden by setting @futureonly = @futurevalue when the
**  procedure is invoked.  In this case existing columns with the user
**  datatype won't have their existing default or rule changed.
*/

/*
**  Check to see that the object names are local to the current database.
*/
if (@objname like "%.%.%")
   or
   (@rulename like "%.%.%" and
	substring(@rulename, 1, charindex(".", @rulename) - 1) != db_name())
begin
	/*
	** 17350, "Rule and table or usertype must be in 'current' database."
	*/
	exec sp_getmessage 17350, @msg output
	print @msg
	return (1)
end

/*
**  Check that the @futureonly argument, if supplied, is correct.
*/
if (@futureonly is not null)
begin
	if (@futureonly != @futurevalue)
	begin
		/*
		** 17351, "Usage: bindrule rulename, objectname [, 'futureonly']"
		*/
		exec sp_getmessage 17351, @msg output
		print @msg
		return (1)
	end
end

/*
**  Check to see that the rule exists and get it's id.
*/
if not exists (select id
	from sysobjects
where id = object_id(@rulename)
	and sysstat & 7 = 7)		/* rule object */

begin
	/*
	** 17352, "No such rule exists.  You must create the rule first."
	*/
	exec sp_getmessage 17352, @msg output
	print @msg
	return (1)
end

/*
** Check to see that the rule is not of declared type
*/

if exists (select * from sysprocedures
		where id = object_id(@rulename)
		and sequence = 0
		and status & 4096 = 4096)
begin
	/*
	** 17358, "You cannot bind a declared constraint. The rule must be created \
using create rule."
	*/
	exec sp_getmessage 17358, @msg output
	print @msg
	return (1)
end

/*
**  If @objname is of the form tab.col then we are binding to a column.
**  Otherwise its a datatype.  In the column case, we need to extract
**  and verify the table and column names and make sure the user owns
**  the table that is getting the rule bound.
*/
if @objname like "%.%"
begin
	declare @tabname varchar(30)		/* name of table */
	declare @colname varchar(30)		/* name of column */

	/*
	**  Get the table name out.
	*/
	select @tabname = substring(@objname, 1, charindex(".", @objname) - 1)
	select @colname = substring(@objname, charindex(".", @objname) + 1, 61)

	/*
	**  If the column type is image, text, or timestamp, disallow the bind.
	**  Rules can't be bound to image, text, or timestamp columns.
	**  The qualification to check for types is a little strange because
	**  text and image are real, basic data types while timestamp is not.
	**  Timestamp is really a binary.  The types are checked in case
	**  there is a user-defined datatype that is an image or text.
	**  User-defined datatypes mapping to timestamp are not allowed
	**  by sp_addtype.
	*/
	if exists (select *
			from sysobjects o, syscolumns c
		where c.id = object_id(@tabname)
			and c.name = @colname
			and c.name = @colname
			and o.id = object_id(@tabname)
			and o.sysstat & 7 = 3
			and (c.type in (35, 34) or c.usertype = 80))
	begin
		/*
		** 17353, "You can't bind a rule to a text, image, or timestamp datatype column."
		*/
		exec sp_getmessage 17353, @msg output
		print @msg
		return (1)
	end

	/*
	** If status of the column does not reflect having more than one
	** check constraint (declared rule), then update the status if
	** it has additional constraint(s).
	*/

	select @status = status, @colid = colid from syscolumns, sysobjects
		where syscolumns.id = object_id(@tabname)
			and syscolumns.name = @colname
			and sysobjects.id = object_id(@tabname)
			and uid = user_id()
			and sysobjects.sysstat & 7 = 3      /* user table */

	/*
	**  Did the bind happen?
	*/
	if @@rowcount != 1
	begin
		/*
		** 17344, "You do not own a column of that name." 
		*/
		exec sp_getmessage 17344, @msg output
		print @msg
		return (1)
	end

	if @status & 16 = 0 and
		exists (select * from sysconstraints c, sysobjects o
				where c.tableid = object_id(@tabname)
					and c.colid = @colid
					and o.id = c.constrid
					and o.sysstat & 7 = 7)
	begin
		update syscolumns
			set domain = object_id(@rulename),
			    status = syscolumns.status | 16
				from syscolumns, sysobjects
			where syscolumns.id = object_id(@tabname)
				and syscolumns.name = @colname
				and sysobjects.id = object_id(@tabname)
				and uid = user_id()
				and sysobjects.sysstat & 7 = 3      /* user table */
	end
	else
	begin
		update syscolumns
			set domain = object_id(@rulename)
				from syscolumns, sysobjects
			where syscolumns.id = object_id(@tabname)
				and syscolumns.name = @colname
				and sysobjects.id = object_id(@tabname)
				and uid = user_id()
				and sysobjects.sysstat & 7 = 3      /* user table */
	end
	/*
	**  Since binding a rule is a schema change, update schema count
	**  for the object in the sysobjects table.
	*/
	update sysobjects
		set schemacnt = schemacnt + 1
			from sysobjects
				where id = object_id(@tabname)
					and uid = user_id()
					and schema_inc(object_id(@tabname)) is NULL

	/*
	** 17354, "Rule bound to table column."
	*/
	exec sp_getmessage 17354, @msg output
	print @msg

end
else
begin
	/*
	**  We're binding to a user type.  In this case, the @objname
	**  is really the name of the user datatype.
	**  When we bind to a user type, any existing columns get changed
	**  to the new binding unless their current binding is not equal
	**  to the current binding for the usertype or if they set the
	**  @futureonly parameter to @futurevalue.
	*/
	declare @oldrule int			/* current rule for type */

	/*
	**  If the column type is image, text, or timestamp, disallow the bind.
	**  Rules can't be bound to image or text columns.
	*/
	if exists (select *
			from systypes
				where name = @objname
					and (type in (35, 34) or usertype = 80))
	begin
		/*
		** 17355, "You can't bind a rule to a text, image, or timestamp datatype."
		*/
		exec sp_getmessage 17355, @msg output
		print @msg
		return (1)
	end

	/*
	**  Get the current rule for the datatype.
	*/
	select @oldrule = domain
		from systypes
	where name = @objname
		and uid = user_id()
		and usertype > 100

	if @oldrule is null
	begin
		/*
		** 17346, "You do not own a datatype of that name." 
		*/
		exec sp_getmessage 17346, @msg output
		print @msg
		return (1)
	end

	update systypes
		set domain = object_id(@rulename)
			from systypes
		where name = @objname
			and uid = user_id()
			and usertype > 100


	/*
	** 17356, "Rule bound to datatype."
	*/
	exec sp_getmessage 17356, @msg output
	print @msg


	/*
	**  Now see if there are any columns with the usertype that
	**  need the new binding.
	*/
	if isnull(@futureonly, "") != @futurevalue
		and exists (select *
			from syscolumns, systypes
				where syscolumns.usertype = systypes.usertype
					and systypes.name = @objname
					and systypes.usertype > 100
					and systypes.uid = user_id()
                                        and (syscolumns.domain = @oldrule
                                          or  syscolumns.domain = 0 )     )
	begin
		/*
		**  Update the table schema to indicate that something
		**  has changed in the table's schema.
		*/
		update sysobjects
			set schemacnt = schemacnt + 1
				from sysobjects, syscolumns, systypes
			where sysobjects.id = syscolumns.id
				and syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()
                                and (syscolumns.domain = @oldrule
                                  or  syscolumns.domain = 0 )
				and sysobjects.id in
					(select s.id from sysobjects s
					where schema_inc(s.id) is NULL)
		/*
		**  Update syscolumns with new binding.
		*/
		update syscolumns
			set domain = systypes.domain
				from syscolumns, systypes
			where syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()
                                and (syscolumns.domain = @oldrule
                                  or  syscolumns.domain = 0 )

		/*
		** 17357, "The new rule has been bound to column(s) of the specified user datatype."
		*/
		exec sp_getmessage 17357, @msg output
		print @msg

	end
end

return (0)

go
exec sp_procxmode 'sp_bindrule', 'anymode'
go
grant execute on sp_bindrule to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_changedbowner')
begin
	drop procedure sp_changedbowner
end
go
print "Installing sp_changedbowner"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/changedbowner */
 
/*
** Messages for "sp_changedbowner"      17360
**
** 17231, "No login with the specified name exists."
** 17361, "Can't change the owner of the master, model, tempdb or sybsystemprocs  database."
** 17362, "The proposed new db owner already is a user in the database or owns the database."
** 17363, "The proposed new db owner already is aliased in the database."
** 17364, "The dependent aliases were mapped to the new dbo."
** 17365, "The dependent aliases were dropped."
** 17366, "Database owner changed."
** 17431, "true"
** 17368, "Your curwrite label needs to be set correctly before you attempt to change the database owner."
*/

create procedure sp_changedbowner
@loginame varchar(30),         /* login to become dbo */
@map      varchar(10) = NULL   /* True to map aliases, else drop  */
as

declare @suid    smallint
declare @oldsuid smallint
declare @msg   	varchar(250)
declare @true   varchar(10)
declare @dbname	varchar(30)



if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  Can't change the owner of the master, model, tempdb or sybsystemprocs  database.
*/
if db_name() in ( "master", "tempdb", "model", "sybsystemprocs" )
begin
	/*
	** 17361, "Can't change the owner of the master database."
	*/
	exec sp_getmessage 17361, @msg output
	print @msg
	return(1)
end


/*
**  Make sure that @loginame exists and has a login.
*/
select @suid = suid
	from master.dbo.syslogins
		where name = @loginame

if @suid is NULL
begin
	/*
	** 17231, "No login with the specified name exists."
	*/
	exec sp_getmessage 17231, @msg output
	print @msg
	return(1)
end

/*
**  Make sure that @loginame isn't already a user or alias in the database.
*/
if exists (select *
		from sysusers
			where suid = @suid)
begin
	/*
	** 17362, "The proposed new db owner already is a user in the database or owns the database."
	*/
	exec sp_getmessage 17362, @msg output
	print @msg
	return(1)
end
if exists (select *
		from sysalternates
			where suid = @suid)
begin
	/*
	** 17363, "The proposed new db owner already is aliased in the database."
	*/
	exec sp_getmessage 17363, @msg output
	print @msg
	return(1)
end

/* 
** find old (current) dbo's suid
*/
select @oldsuid = suid
	from sysusers
		where uid = 1


begin transaction

/*
**  Now change the suid of the owner of the database to the suid of @loginame.
*/
update sysusers
	set suid = @suid
		where uid = 1

/*
** if the user requested that aliases be mapped to new dbo, do that.
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
if lower(@map) in ("true", @true)
begin

	if exists (select *
			from sysalternates
				where altsuid = @oldsuid)
	begin
		update sysalternates
			set altsuid = @suid
				where altsuid = @oldsuid

		/*
		** 17364, "The dependent aliases were mapped to the new dbo."
		*/
		exec sp_getmessage 17364, @msg output
		print @msg
	end
end
/* else drop the aliases to the old dbo */
else
begin

	if exists (select *
			from sysalternates
				where altsuid = @oldsuid)
	begin
		delete from sysalternates
			where altsuid = @oldsuid

		  
		/*
		** 17365, "The dependent aliases were dropped."
		*/
		exec sp_getmessage 17365, @msg output
		print @msg
	end
end

/*
**  Reflect the new owner of the database in master.dbo.sysdatabases.
*/
update master.dbo.sysdatabases
	set suid = @suid
		where dbid = db_id()

commit transaction


/*
** Update the dbinfo and dbtable uid fields for this database.
*/
select @dbname = db_name()
dbcc dbrepair(@dbname, "updowner")

/*
** 17366, "Database owner changed."
*/
exec sp_getmessage 17366, @msg output
print @msg
return (0)
go
exec sp_procxmode 'sp_changedbowner', 'anymode'
go
grant execute on sp_changedbowner to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_aux_getsize')
begin
	drop procedure sp_aux_getsize
end
go
print "Installing sp_aux_getsize"
go

/* This stored procedure is for parsing a size string of the form:
**		 "%f[pPkKmMgG]
** and return the value in equivalent "k" units if @format_str is NULL.
** If a format string is specified then another conversion to the required
** format is done. @output_str has the string equivalent of the return value.
** If a format string is specified then @ret_size value will be set to 0.
** For example sp_aux_getsize "1024K",@ret_size, "M" will put 1 in @ret_size.
**
**	Messages for sp_aux_getsize
** 
** 18146, "Syntax error encountered.  Sizes must be of the form 
**   	   %d[k | m | g | p]. " 
**
** 18149, "Invalid size of %1! encountered. Sizes must be greter than zero."
*/
create procedure sp_aux_getsize
@size_str		varchar(30),
@ret_size		int output,
@input_size		int = NULL,
@output_str		varchar(30) = NULL output
as

declare @unit_loc		int
declare @size			int
declare @multiplier		int
declare @int_loc		int
declare @unit_str		char(1)
declare @size_part_str		varchar(30)
declare @msg			varchar(255)
declare @float_size		float


/*
**  Parse the wash size string
*/
select @unit_loc = patindex("%[kKmMgGpP]%", @size_str)

/*
**  If the units have been specified grab them, otherwise default to
**  units of kilobytes.
*/
if @unit_loc != 0
begin
	select @unit_str = substring(@size_str, @unit_loc, 1)
	select @size_part_str = substring(@size_str, 1, @unit_loc - 1)
end
else
begin
	if patindex("%[a-z]%", @size_str) != 0
	begin
		exec sp_getmessage 18146, @msg output
		print @msg
		return 0
	end

	select @int_loc = patindex("%[0-9]%", @size_str)
	select @size_part_str = substring(@size_str, @int_loc, 
					char_length(@size_str))
	select @unit_str = "k"
end

if @size_part_str = NULL
begin
	exec sp_getmessage 18146, @msg output
	print @msg
	select @ret_size = 0
	return 0
end

if @input_size is NULL
begin
	select @float_size = convert(float, @size_part_str)

	if @float_size < 0
	begin
		select @size_str = rtrim(@size_str)
		exec sp_getmessage 18149, @msg output
		print @msg, @size_str
		return 0
	end

	if (@unit_str = "p" or @unit_str = "P")
		select @float_size = @float_size * @@pagesize / 1024
	else if (@unit_str = "m" or @unit_str = "M")
		select @float_size = @float_size * 1024 
	else if (@unit_str = "g" or @unit_str = "G")
		select @float_size = @float_size * 1024 * 1024
end
else
begin
	select @float_size = @input_size
end
	
if @input_size is not NULL
begin
	/* Here the input size is assumed to be in K units */
	if (@unit_str = "p" or @unit_str = "P")
		select @float_size = @float_size / (@@pagesize / 1024)
	else if (@unit_str = "m" or @unit_str = "M")
		select @float_size = @float_size / 1024 
	else if (@unit_str = "g" or @unit_str = "G")
		select @float_size = @float_size /(1024 * 1024) 
end

/*
**  Now round config size to the nearest integer value since
**  we'll be inserting this into sysconfigures as the integer
**  representation of the number of kilobytes for this size of this
**  cache.  But if a format string is given as an input, round it off
**  to the 4 digit precision after a decimal point.
*/
if @input_size is not NULL
begin
	select @ret_size = 0
	select @output_str = ltrim(str(round(@float_size, 4),15,4)) + @unit_str
end
else
begin
	select @ret_size = convert(int, round(@float_size, 0))
end
return 1
go
exec sp_procxmode 'sp_aux_getsize', 'anymode'
go
grant execute on sp_aux_getsize to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_expandbitmap')
begin
	drop procedure syb_aux_expandbitmap
end
go
print "Installing syb_aux_expandbitmap"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */


create procedure syb_aux_expandbitmap
@colcount     smallint,			/* no of columns in the table */
@expandmap    varbinary(32) output      /* expanded column map with all 1's */
as

declare @colleft smallint  /* tracks number of columns left in the bit map */


/* 
** if the number of columns are less than 8, it is a special case because
** bit 0 is treated differently in the column bit map
*/
if (@colcount < 8)
begin
      if (@colcount = 1)
 	   select @expandmap = 0x02
      else if (@colcount = 2)
           select @expandmap = 0x06
      else if (@colcount = 3)
	   select @expandmap = 0x0e
      else if (@colcount = 4)
	   select @expandmap = 0x1e
      else if (@colcount = 5)
	   select @expandmap = 0x3e
      else if (@colcount = 6)
	   select @expandmap = 0x7e
      else if (@colcount = 7)
	   select @expandmap = 0xfe
      return
end

/*
** column count was more than 7, thus set up the bit map for the first byte
** and set the column left variable
*/
select @expandmap = 0xfe
select @colleft = @colcount - 7

/* 
** for chunk of 8 columns, set the bit map to all 1s for that byte
*/
while (@colleft >= 8)
begin
     select @expandmap = @expandmap + 0xff
     select @colleft = @colleft - 8
end

/*
** if no column left, return 
*/
if (@colleft = 0)
    return

/* 
** now the number of left columns has to be between 1 and 7. So setup
** the bit map for the last byte
*/
if (@colleft = 1)
     select @expandmap = @expandmap + 0x01
else if (@colleft = 2)
     select @expandmap = @expandmap + 0x03
else if (@colleft = 3)
     select @expandmap = @expandmap + 0x07
else if (@colleft = 4)
     select @expandmap = @expandmap + 0x0f
else if (@colleft = 5)
     select @expandmap = @expandmap + 0x1f
else if (@colleft = 6)
     select @expandmap = @expandmap + 0x3f
else if (@colleft = 7)
     select @expandmap = @expandmap + 0x7f

go
exec sp_procxmode 'syb_aux_expandbitmap', 'anymode'
go
grant execute on syb_aux_expandbitmap to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privexor')
begin
	drop procedure syb_aux_privexor
end
go
print "Installing syb_aux_privexor"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */


create procedure syb_aux_privexor
@left_binary	varbinary (32),	       /* left operand for the subtract */
@right_binary	varbinary (32),        /* right operand for the subtract */	
@col_count	smallint,	       /* number of columns in the table */
@result_binary	varbinary (32) output  /* result of the subtract operation */
as

declare @loop_count tinyint        /* loop count for all 32 bytes in the varbinary */
declare @left_opr   tinyint	   /* integer representation of the left operand */
declare @right_opr  tinyint	   /* integer representation of the right operand */
declare @result_opr tinyint	   /* result of subtract operation */
declare @left_bin   varbinary (32) /* expanded with 1's left operand */
declare @loop_bound tinyint 	   /* stores the loop upper bound */
/*
** initialize the loop_count
*/
select @loop_count = 1

/* 
** initialize loop_bound
*/
select @loop_bound = @col_count/8 + 1

/* 
** check for boundary condition. If right operand is 0, there is nothing to subtract
*/
if (@right_binary = 0x00)
begin
      select @result_binary = @left_binary
      return
end

/*
** check for boundary condition. If both oerands are equal, the result has to be 0
*/
if ((@left_binary = 0x01) and (@right_binary = 0x01))
begin
      select @result_binary = 0x00
      return
end

/* 
** if the left oeprand is 0x01, the right operand can't be 0x01. Now we need to expand
** the left opernad in order to subtract correctly
*/
if (@left_binary = 0x01)
     exec sybsystemprocs.dbo.syb_aux_expandbitmap @col_count, @left_bin output
else
    select @left_bin = @left_binary

/*
** loop for all relevant bytes in the var binary operand 
*/
while (@loop_count <= @loop_bound)
begin
      select @left_opr = convert (tinyint (1), substring (@left_bin, @loop_count, 1))
      select @right_opr = convert (tinyint (1), substring (@right_binary, @loop_count, 1))

      /* do the binary operation */
      select @result_opr = @left_opr ^ @right_opr
      if (@loop_count = 1)
      begin
	   select @result_binary = convert (binary (1), @result_opr)
      end
      else
      begin
	   select @result_binary = @result_binary + convert (binary (1), @result_opr)
      end

      select @loop_count = @loop_count + 1
end
go
exec sp_procxmode 'syb_aux_privexor', 'anymode'
go
grant execute on syb_aux_privexor to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privnots')
begin
	drop procedure syb_aux_privnots
end
go
print "Installing syb_aux_privnots"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */


create procedure syb_aux_privnots
@left_binary	varbinary (32),   	/* operand for the complement */
@col_count	smallint,  	  	/* number of columns in the table */
@result_binary	varbinary (32) output	/* result of the complement */
as

declare @loop_count tinyint		/* loop counter for 32 bytes in varbinary */
declare @left_opr   tinyint		/* integer represenation of a byte in left operand */
declare @right_opr  tinyint		/* integer representation of a byte in right opr */
declare @result_opr tinyint		/* result integer byte */
declare @expand_bin varbinary (32)	/* expanded bit map with all 1s */	
declare @temp_resbin varbinary (32)	/* transient value store for the result */
declare @loop_bound tinyint 	   /* stores the loop upper bound */


/*
** initialize the loop_count
*/

select @loop_count = 1

/* 
** initialize loop_bound
*/
select @loop_bound = @col_count/8 + 1

/* 
** boundary condition. If left operand is 0, then the NOT of that is all 1s
*/
if (@left_binary = 0x00) 
begin
      select @result_binary = 0x01
      return
end

/*
** if left operand is all 1s, then NOT of of it is all 0s
*/
if (@left_binary = 0x01)
begin
      select @result_binary = 0x00
      return
end

/*
** loop for each byte of 32 bytes varbinary operand
*/
while (@loop_count <= @loop_bound)
begin
      select @left_opr = convert (tinyint (1), substring (@left_binary, @loop_count, 1))
      
      select @result_opr = ~@left_opr /* complement the byte */


      /*
      ** first byte is treated differently as there is nothing to concatenate
      */
      if (@loop_count = 1)
      begin
	   select @result_opr = @result_opr & 0xfe  /* do this as bit 0 has a special
						       meaning. make it 0 */
	   select @temp_resbin = convert (binary (1), @result_opr)
      end
      else
      begin
	   select @temp_resbin = @temp_resbin + convert (binary (1), @result_opr)
      end

      select @loop_count = @loop_count + 1
end


/* need to zero out the unnecessary one's  */
exec sybsystemprocs.dbo.syb_aux_expandbitmap @col_count, @expand_bin output

select @loop_count = 1

/*
** the temp_resbin has 1's beyond number of columns. We need to zero them out
*/
while (@loop_count <= @loop_bound)
begin
      select @left_opr = convert (tinyint (1), substring (@temp_resbin, @loop_count, 1))
      select @right_opr = convert (tinyint (1), substring (@expand_bin, @loop_count, 1))
      select @result_opr = @left_opr & @right_opr

      if (@loop_count = 1)
      begin
	   select @result_binary = convert (binary (1), @result_opr)
      end
      else
      begin
	   select @result_binary = @result_binary + convert (binary (1), @result_opr)
      end

      select @loop_count = @loop_count + 1
end
go
exec sp_procxmode 'syb_aux_privnots', 'anymode'
go
grant execute on syb_aux_privnots to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privsand')
begin
	drop procedure syb_aux_privsand
end
go
print "Installing syb_aux_privsand"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */


create procedure syb_aux_privsand
@left_binary	varbinary (32),	      /* left operand of AND */
@right_binary	varbinary (32),       /* right operand of AND */
@col_count	smallint,	      /* number of columns in the table */
@result_binary	varbinary (32) output /* result of ANDing */
as

declare @loop_count tinyint   	   /* loop counter for the 32 bytes in varbinary operand */
declare @left_opr   tinyint	   /* integer represenation of a byte in left opr */
declare @right_opr  tinyint	   /* integer represenation of a byte in right opr */
declare @result_opr tinyint	   /* result byte */
declare @left_bin   varbinary (32) /* expanded bit map of left operand */
declare @right_bin  varbinary (32) /* expanded bit map of right operand */
declare @loop_bound tinyint 	   /* stores the loop upper bound */

/*
** initialize the loop count
*/
select @loop_count = 1

/* 
** initialize loop_bound
*/
select @loop_bound = @col_count/8 + 1

/*
** boundary condition. If any of the operand is 0, the result will be zero 
*/
if ((@right_binary = 0x00) or (@left_binary = 0x00))
begin
      select @result_binary = 0x00
      return
end

/*
** boundary condition. If both operands are all 1's, return all 1's
*/

if ((@left_binary = 0x01) and (@right_binary = 0x01))
begin
      select @result_binary = 0x01
      return
end

/* 
** if left operand was all 1's, expand it into appropriate number of columns 
*/
if (@left_binary = 0x01)
     exec sybsystemprocs.dbo.syb_aux_expandbitmap @col_count, @left_bin output
else
     select @left_bin = @left_binary

/*
** if right operand was all 1's, expand it into appropriate number of columns 
*/

if (@right_binary = 0x01)
     exec sybsystemprocs.dbo.syb_aux_expandbitmap @col_count, @right_bin output
else
     select @right_bin = @right_binary


/*
** loop for each byte in the varbinary operand
*/
while (@loop_count <= @loop_bound)
begin
      select @left_opr = convert (tinyint (1), substring (@left_bin, @loop_count, 1))
      select @right_opr = convert (tinyint (1), substring (@right_bin, @loop_count, 1))

      /* bit wise ANDing. Note atmost only one of the operands might have been
         expanded to full 32 bytes. The extra 1s will ge zeroed out in the operation */

      select @result_opr = @left_opr & @right_opr

      /*
      ** first byte is treated differently as there is nothing to be appended 
      */
      if (@loop_count = 1)
      begin
	   select @result_binary = convert (binary (1), @result_opr)
      end
      else
      begin
	   select @result_binary = @result_binary + convert (binary (1), @result_opr)
      end

      select @loop_count = @loop_count + 1
end
go
exec sp_procxmode 'syb_aux_privsand', 'anymode'
go
grant execute on syb_aux_privsand to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_privunion')
begin
	drop procedure syb_aux_privunion
end
go
print "Installing syb_aux_privunion"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */


create procedure syb_aux_privunion
@left_binary	varbinary (32),        /* left operand of UNION operation */
@right_binary	varbinary (32),        /* right operand of UNION operation */
@col_count	smallint,  	  	/* number of columns in the table */
@result_binary	varbinary (32) output  /* operand to return the result into */
as

declare @loop_count tinyint   /* loop count for all 32 bytes in varbinary */
declare @left_opr   tinyint   /* integer representation of a byte in left operand */
declare @right_opr  tinyint   /* integer representation of a byte in right operand */
declare @result_opr tinyint   /* result of anding two bytes */
declare @loop_bound tinyint 	   /* stores the loop upper bound */

/* 
** initialize the loop count 
*/
select @loop_count = 1

/* 
** initialize loop_bound
*/
select @loop_bound = @col_count/8 + 1

/*
** check for boundary conditions. If any of the operand is all one's, the result
** will also be all ones
*/
if ((@left_binary = 0x01) or (@right_binary = 0x01))
begin
      select @result_binary = 0x01
      return
end
/*
** loop through all the bytes in the operand and compute the UNION (i.e OR) byte
** by byte 
*/

While (@loop_count <= @loop_bound)
begin
      select @left_opr = convert (tinyint (1), substring (@left_binary, @loop_count, 1))
      select @right_opr = convert (tinyint (1), substring (@right_binary, @loop_count, 1))
      select @result_opr = @left_opr | @right_opr

  
      if (@loop_count = 1)
      Begin
	   /* first bytes is treated differently, as there is nothing to 
           ** be concatenated 
	   */
	   select @result_binary = convert (binary (1), @result_opr)
      end
      else
      begin
	   /* 
	   ** concatenate the result from byte 2 onwards 
	   */
	   select @result_binary = @result_binary + convert (binary (1), @result_opr)
      end

      select @loop_count = @loop_count + 1
end
go
exec sp_procxmode 'syb_aux_privunion', 'anymode'
go
grant execute on syb_aux_privunion to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_colbit')
begin
	drop procedure syb_aux_colbit
end
go
print "Installing syb_aux_colbit"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure syb_aux_colbit (
@col_pos	smallint,
@columns	varbinary (32),
@result		tinyint output )
as

declare @which_byte	tinyint
declare @bit_offset	tinyint
declare @bitmap_byte	tinyint

/*
** check to see if the bit 0 is 1. If it is, then the privilege is 
** available on all columns 
*/

if (@columns = 0x01)
begin
	select @result = 1
	return 
end

select @result = 0
select @which_byte = (@col_pos)/8 
select @bit_offset = @col_pos - @which_byte * 8



/* get the byte of the bit map we are interested in */
select @bitmap_byte = convert (tinyint(1), substring (@columns, @which_byte + 1, 1))

if (@bit_offset = 0)
	select @result = @bitmap_byte & 0x01
else if (@bit_offset = 1)
	select @result = @bitmap_byte & 0x02
else if (@bit_offset = 2)
	select @result = @bitmap_byte & 0x04
else if (@bit_offset = 3)
	select @result = @bitmap_byte & 0x08
else if (@bit_offset = 4)
	select @result = @bitmap_byte & 0x10
else if (@bit_offset = 5)
	select @result = @bitmap_byte & 0x20
else if (@bit_offset = 6)
	select @result = @bitmap_byte & 0x40
else if (@bit_offset = 7)
	select @result = @bitmap_byte & 0x80

go
exec sp_procxmode 'syb_aux_colbit', 'anymode'
go
grant execute on syb_aux_colbit to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'syb_aux_printprivs')
begin
	drop procedure syb_aux_printprivs
end
go
print "Installing syb_aux_printprivs"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure syb_aux_printprivs (
	@calledfrom_colpriv	tinyint,
	@col_pos		tinyint,
	@tab_priv		tinyint,
	@tab_priv_g		tinyint,
	@col_priv		varbinary (32),
	@col_priv_g		varbinary (32),
	@colprivileges		tinyint,
	@grantable		varchar (3) output,
        @is_printable		tinyint output)
as
     declare @bitset		tinyint
     declare @bitset_g		tinyint

     select @grantable = 'NO'
     select @is_printable = 0
     /* 
     ** check if the privilege info is to be computed for a table level privilege
     ** i.e. for insert or delete
     */
     if (@colprivileges = 0)
     begin
	   begin
		if ((@tab_priv = 0) and (@tab_priv_g = 0))
		/* no privileges on any column of this table */
			return (0)

		if (@tab_priv_g <> 0x00)
			select @grantable = 'YES'

	   end		
	   select @is_printable = 1
	   return (0)
     end


     /*
     ** The privilege information is to be printed for column level
     ** i.e. select, update, reference
     */

     if ((@col_priv = 0x00) and (@col_priv_g = 0x00))
	  /* empty bit map..so nothing to be printed */
	  return (0)

     if (@calledfrom_colpriv = 0)
     /* we are printing privileges for sp_table_privilege procedure call. Thus
	if any of the bit is one, the privilege is printable */

     begin
	  if (@col_priv_g <>  0x00)
	 	select @grantable = 'YES'

	  select @is_printable = 1
	  return (0)
     end

     /* 
     ** we are called from sp_column_privileges . Need to check if the colbit specified
     ** by the @col_pos is set or not
     */
     exec sybsystemprocs.dbo.syb_aux_colbit @col_pos, @col_priv_g, @bitset_g output

     if (@bitset_g > 0)
	   select @grantable = 'YES'

     exec sybsystemprocs.dbo.syb_aux_colbit @col_pos, @col_priv, @bitset output

     /*
     ** if none of the bits are set, return
     */
     if ((@bitset = 0) and (@bitset_g = 0))
	  return (0)

     /*
     ** the privilege is printable
     */

     select @is_printable = 1
     return (0)

go
exec sp_procxmode 'syb_aux_printprivs', 'anymode'
go
grant execute on syb_aux_printprivs to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_aux_computeprivs')
begin
	drop procedure sp_aux_computeprivs
end
go
print "Installing sp_aux_computeprivs"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure sp_aux_computeprivs ( 
                        @table_name  	 	varchar(32),
                        @table_owner 	 	varchar(32),
                        @table_qualifier 	varchar(32), 
			@column_name	 	varchar(32),
			@calledfrom_colpriv	tinyint,
			@tab_id		 	int)

as        

    declare @low 		int		/* range of userids to check */
    declare @high 		int
    declare @max_uid		smallint        /* max uid allowed for a user */
    declare @grantor_name	varchar (32)    /* the ascii name of grantor. used for output */
    declare @grantee_name	varchar (32)    /* the ascii name of grantee. used for output */
    declare @col_count		smallint        /* number of columns in @table_name */
    declare @grantee    	smallint	/* id of the grantee */
    declare @action 		tinyint	 	/* action refers to select, update...*/
    declare @columns		varbinary (32)	/* bit map of column privilegs */
    declare @protecttype 	tinyint		/* grant/revoke or grant with grant option */
    declare @grantor    	smallint	/* id of the grantor of the privilege */
    declare @grp_id		smallint	/* the group a user belongs to */
    declare @grant_type		tinyint		/* used as a constant */
    declare @revoke_type	tinyint		/* used as a constant */
    declare @select_action	tinyint		/* used as a constant */
    declare @update_action	tinyint		/* used as a constant */
    declare @reference_action	tinyint		/* used as a constant */
    declare @insert_action	tinyint		/* used as a constant */
    declare @delete_action	tinyint		/* used as a constant */
    declare @public_select	varbinary (32)  /* stores select column bit map for public */
    declare @public_reference	varbinary (32)	/* stores reference column bit map for public */
    declare @public_update	varbinary (32)	/* stores update column bit map for public */
    declare @public_insert	tinyint		/* stores if insert has been granted to public */
    declare @public_delete	tinyint		/* store if delete has been granted to public */
    declare @grp_select		varbinary (32)  /* stores select column bit map for group */
    declare @grp_update		varbinary (32)  /* stores update column bit map for group */
    declare @grp_reference	varbinary (32)  /* stores reference column bit map for group */
    declare @grp_delete		tinyint		/* if group hs been granted delete privilege */
    declare @grp_insert		tinyint		/* if group has been granted insert privilege */
    declare @inherit_select	varbinary (32)	/* stores select column bit map for 
						   inherited privs*/
    declare @inherit_update	varbinary (32)  /* stores update column bit map for 
						   inherited privs */
    declare @inherit_reference	varbinary (32)  /* stores reference column bit map for 
						   inherited privs */
    declare @inherit_insert	tinyint		/* inherited insert priv */
    declare @inherit_delete	tinyint		/* inherited delete priv */
    declare @select_go		varbinary (32)	/* user column bit map of select with grant */
    declare @update_go		varbinary (32)	/* user column bit map of update with grant */
    declare @reference_go	varbinary (32)	/* user column bitmap of reference with grant */
    declare @insert_go		tinyint		/* user insert priv with grant option */
    declare @delete_go		tinyint		/* user delete priv with grant option  */
    declare @prev_grantor	tinyint		/* used to detact if the grantor has changed 
						   between two consecutive tuples */
    declare @col_pos		tinyint		/* col_pos of the column we are interested in. It
						   is used to find the col-bit in the bitmap */
    declare @owner_id		smallint	/* id of the owner of the table */
    declare @dbid		smallint	/* dbid for the table */
    declare @grantable		varchar (3) 	/* 'YES' or 'NO' if the privilege is grantable or
						   not */
    declare @is_printable	tinyint		/* 1, if the privilege info is to be outputted */
    declare @curr_column	varchar (32)    /* name of the column being printed */
/* 
** Initialize all constants to be used in this procedure
*/

    select @grant_type = 1

    select @revoke_type = 2
   
    select @select_action = 193

    select @reference_action = 151

    select @update_action = 197

    select @delete_action = 196

    select @insert_action = 195

    select @max_uid = 16383

    select @low = -16383, @high = 32767
    select @dbid = db_id()

/* 
** compute the table owner id
*/

    select @owner_id = uid
    from   sysobjects
    where  id = @tab_id

/*
** create a temporary sysprotects table that only has grant/revoke tuples
** for the requested table. This is done as an optimization as the sysprotects
** table may need to be traversed several times
*/

    create table #sysprotects
	(uid		smallint,
	 action		tinyint,
	 protecttype	tinyint,
	 columns	varbinary (32) NULL,
	 grantor	smallint)

/*
** This table contains all the groups including PUBLIC that users, who
** have been granted privilege on this table, belong to. Also it includes
** groups that have been explicitly granted privileges on the table object
*/
    create table #useful_groups
	(grp_id		smallint)

/*
** create a table that contains the list of grantors for the object requested.
** We will do a cartesian product of this table with sysusers in the
** current database to capture all grantor/grantee tuples
*/

    create table #distinct_grantors
	(grantor	smallint)

/*
** We need to create a table which will contain a row for every object
** privilege to be returned to the client.  
*/

    create table #column_privileges 
	(grantee_gid	smallint,
	 grantor	smallint,
	 grantee	smallint,
	 insertpriv	tinyint,
	 insert_go	tinyint NULL,
	 deletepriv	tinyint,
	 delete_go	tinyint NULL,
	 selectpriv	varbinary (32) NULL,
	 select_go	varbinary (32) NULL,
	 updatepriv	varbinary (32) NULL,
	 update_go	varbinary (32) NULL,
	 referencepriv	varbinary (32) NULL,
	 reference_go	varbinary (32) NULL)

/*
** Results Table
*/
    create table #results_table
	 (table_qualifier	varchar (32),
	  table_owner		varchar (32),
	  table_name		varchar (32),
	  column_name		varchar (32) NULL,
	  grantor		varchar (32),
	  grantee 		varchar (32),
	  privilege		varchar (32),
	  is_grantable		varchar (3))
/*
** this cursor scans the distinct grantor, group_id pairs
*/
    declare grp_cursor cursor for
	select distinct grp_id, grantor 
	from #useful_groups, #distinct_grantors
	order by grantor

/* 
** this cursor scans all the protection tuples that represent
** grant/revokes to users only
*/
    declare user_protect cursor for
	select uid, action, protecttype, columns, grantor
	from   #sysprotects
	where  (uid != 0) and
	       (uid <= @max_uid)


/*
** this cursor is used to scan #column_privileges table to output results
*/
    declare col_priv_cursor cursor for
	  select grantor, grantee, insertpriv, insert_go, deletepriv, delete_go,
		 selectpriv, select_go, updatepriv, update_go, referencepriv, reference_go
	  from #column_privileges



/*
** column count is needed for privilege bit-map manipulation
*/
    select @col_count = count (*) 
    from   syscolumns
    where  id = @tab_id


/* 
** populate the temporary sysprotects table #sysprotects
*/

	insert into #sysprotects 
		select uid, action, protecttype, columns, grantor
		from sysprotects
		where (id = @tab_id)    	   and
		      ((action = @select_action)   or
		      (action = @update_action)    or
		      (action = @reference_action) or
		      (action = @insert_action)    or
		      (action = @delete_action))

/* 
** insert privilege tuples for the table owner. There is no explicit grants
** of these privileges to the owner. So these tuples are not there in sysprotects
** table
*/

	insert into #sysprotects
	     values (@owner_id, @select_action, 0, 0x01, @owner_id)
	insert into #sysprotects
	     values (@owner_id, @update_action, 0, 0x01, @owner_id)
	insert into #sysprotects
	     values (@owner_id, @reference_action, 0, 0x01, @owner_id)
	insert into #sysprotects
	     values (@owner_id, @insert_action, 0, 0x00, @owner_id)
	insert into #sysprotects
	     values (@owner_id, @delete_action, 0, 0x00, @owner_id)

/* 
** populate the #distinct_grantors table with all grantors that have granted
** the privilege to users or to gid or to public on the table_name
*/

    insert into #distinct_grantors 
	  select distinct grantor from #sysprotects

/* 
** Populate the #column_privilegs table as a cartesian product of the table
** #distinct_grantors and all the users, other than groups, in the current database
*/


    insert into #column_privileges
	  select gid, g.grantor, su.uid, 0, 0, 0, 0, 0x00, 0x00, 0x00, 0x00, 0x00,
                 0x00
	  from sysusers su, #distinct_grantors g
	  where (su.uid != 0) and
	        (su.uid <= @max_uid)

/*
** populate #useful_groups with only those groups whose members have been granted/revoked
** privilges on the @tab_id in the current database. It also contains those groups
** that have been granted/revoked privileges explicitly
*/

    insert into #useful_groups
	select distinct gid
	from   sysusers su, #sysprotects sp
	where  (su.uid = sp.uid) 


    open grp_cursor

    fetch grp_cursor into @grp_id, @grantor

    /* 
    ** This loop computes all the inherited privilegs of users due
    ** their membership in a group
    */

    while (@@sqlstatus != 2)
   
    begin

	 /* 
	 ** initialize variables 
	 */
	 select @public_select = 0x00
 	 select @public_update = 0x00
	 select @public_reference = 0x00
	 select @public_delete = 0
	 select @public_insert = 0


	 /* get the select privileges granted to PUBLIC */

	 if (exists (select * from #sysprotects 
 		     where (grantor = @grantor) and 
			   (uid = 0) and
			   (action = @select_action)))
	 begin
	      /* note there can't be any revoke row for PUBLIC */
	      select @public_select = columns
	      from #sysprotects
	      where (grantor = @grantor) and 
		    (uid = 0) and
		    (action = @select_action)
         end


	 /* get the update privilege granted to public */
	 if (exists (select * from #sysprotects 
 		     where (grantor = @grantor) and 
			   (uid = 0) and
			   (action = @update_action)))
	 begin
	      /* note there can't be any revoke row for PUBLIC */
	      select @public_update = columns
	      from #sysprotects
	      where (grantor = @grantor) and 
		    (uid = 0) and
		    (action = @update_action)
         end

	 /* get the reference privileges granted to public */
	 if (exists (select * from #sysprotects 
 		     where (grantor = @grantor) and 
			   (uid = 0) and
			   (action = @reference_action)))
	 begin
	      /* note there can't be any revoke row for PUBLIC */
	      select @public_reference = columns
	      from #sysprotects
	      where (grantor = @grantor) and 
		    (uid = 0) and
		    (action = @reference_action)
         end


	 /* get the delete privilege granted to public */
	 if (exists (select * from #sysprotects 
 		     where (grantor = @grantor) and 
			   (uid = 0) and
			   (action = @delete_action)))
	 begin
	      /* note there can't be any revoke row for PUBLIC */
	      select @public_delete = 1
         end

	 /* get the insert privileges granted to public */
	 if (exists (select * from #sysprotects 
 		     where (grantor = @grantor) and 
			   (uid = 0) and
			   (action = @insert_action)))
	 begin
	      /* note there can't be any revoke row for PUBLIC */
	      select @public_insert = 1
         end


	 /*
	 ** initialize group privileges 
	 */

	 select @grp_select = 0x00
	 select @grp_update = 0x00
	 select @grp_reference = 0x00
	 select @grp_insert = 0
	 select @grp_delete = 0

	 /* 
	 ** if the group id is other than PUBLIC, we need to find the grants to
	 ** the group also 
	 */

	 if (@grp_id <> 0)
	 begin
	 	/* find select privilege granted to group */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @grant_type) and
			          (action = @select_action)))
	 	begin
	      		select @grp_select = columns
	      		from #sysprotects
	      		where (grantor = @grantor) and 
		   	      (uid = @grp_id) and
			      (protecttype = @grant_type) and 
		    	      (action = @select_action)
                end

		/* find update privileges granted to group */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @grant_type) and
			          (action = @update_action)))
	 	begin
	      		select @grp_update = columns
	      		from #sysprotects
	      		where (grantor = @grantor) and 
		   	      (uid = @grp_id) and
			      (protecttype = @grant_type) and 
		    	      (action = @update_action)
                end

		/* find reference privileges granted to group */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @grant_type) and
			          (action = @reference_action)))
	 	begin
	      		select @grp_reference = columns
	      		from #sysprotects
	      		where (grantor = @grantor) and 
		   	      (uid = @grp_id) and
			      (protecttype = @grant_type) and 
		    	      (action = @reference_action)
                end

		/* find delete privileges granted to group */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @grant_type) and
			          (action = @delete_action)))
	 	begin

	      		select @grp_delete = 1
                end

		/* find insert privilege granted to group */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @grant_type) and
			          (action = @insert_action)))
	 	begin

	      		select @grp_insert = 1

                end
		
	 end

	 /* at this stage we have computed all the grants to PUBLIC as well as
	 ** the group by a specific grantor that we are interested in. Now we will
	 ** use this info to compute the overall inherited privilegs by the users
	 ** due to their membership to the group or to PUBLIC 
	 */


	 exec sybsystemprocs.dbo.syb_aux_privunion @public_select, @grp_select, @col_count,
					   @inherit_select output
	 exec sybsystemprocs.dbo.syb_aux_privunion @public_update, @grp_update, @col_count,
					   @inherit_update output
	 exec sybsystemprocs.dbo.syb_aux_privunion @public_reference, @grp_reference, @col_count,
					   @inherit_reference output

	 select @inherit_insert = @public_insert + @grp_insert
	 select @inherit_delete = @public_delete + @grp_delete

	 /*
	 ** initialize group privileges to store revokes
	 */

	 select @grp_select = 0x00
	 select @grp_update = 0x00
	 select @grp_reference = 0x00
	 select @grp_insert = 0
	 select @grp_delete = 0

         /* 
	 ** now we need to find if there are any revokes on the group under
 	 ** consideration. We will subtract all privileges that are revoked from the 
	 ** group from the inherited privileges
	 */

	 if (@grp_id <> 0)
	 begin
		/* check if there is a revoke row for select privilege*/
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @revoke_type) and
			          (action = @select_action)))
	 	begin
	      		select @grp_select = columns
	      		from #sysprotects
	      		where (grantor = @grantor) and 
		   	      (uid = @grp_id) and
			      (protecttype = @revoke_type) and 
		    	      (action = @select_action)
                end

		/* check if there is a revoke row for update privileges */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @revoke_type) and
			          (action = @update_action)))
	 	begin
	      		select @grp_update = columns
	      		from #sysprotects
	      		where (grantor = @grantor) and 
		   	      (uid = @grp_id) and
			      (protecttype = @revoke_type) and 
		    	      (action = @update_action)
                end

		/* check if there is a revoke row for reference privilege */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @revoke_type) and
			          (action = @reference_action)))
	 	begin
	      		select @grp_reference = columns
	      		from #sysprotects
	      		where (grantor = @grantor) and 
		   	      (uid = @grp_id) and
			      (protecttype = @revoke_type) and 
		    	      (action = @reference_action)
                end

		/* check if there is a revoke row for delete privilege */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @revoke_type) and
			          (action = @delete_action)))
	 	begin
	      		select @grp_delete = 1
                end

		/* check if there is a revoke row for insert privilege */
	 	if (exists (select * from #sysprotects 
 		            where (grantor = @grantor) and 
			          (uid = @grp_id) and
				  (protecttype = @revoke_type) and
			          (action = @insert_action)))
	 	begin
	      		select @grp_insert = 1

                end


		/* 
		** now subtract the revoked privileges from the group
		*/

		exec sybsystemprocs.dbo.syb_aux_privexor @inherit_select,
					 	 @grp_select,
						 @col_count,
						 @inherit_select output

		exec sybsystemprocs.dbo.syb_aux_privexor @inherit_update,
					 	 @grp_update,
						 @col_count,
						 @inherit_update output

		exec sybsystemprocs.dbo.syb_aux_privexor @inherit_reference,
					 	 @grp_reference,
						 @col_count,
						 @inherit_reference output

		if (@grp_delete = 1)
			select @inherit_delete = 0

		if (@grp_insert = 1)
			select @inherit_insert = 0

	 end

	 /*
	 ** now update all the tuples in #column_privileges table for this
	 ** grantor and group id
	 */
	
	 update #column_privileges
	 set
		insertpriv 	= @inherit_insert,
		deletepriv 	= @inherit_delete,
	        selectpriv 	= @inherit_select,
		updatepriv 	= @inherit_update,
		referencepriv 	= @inherit_reference

	 where (grantor     = @grantor) and
	       (grantee_gid = @grp_id)


	 /*
	 ** the following update updates the privileges for those users
	 ** whose groups have not been explicitly granted privileges by the
	 ** grantor. So they will all have all the privileges of the PUBLIC
	 ** that were granted by the current grantor
	 */

	 select @prev_grantor = @grantor	 
         fetch grp_cursor into @grp_id, @grantor

	 if ((@prev_grantor <> @grantor) or (@@sqlstatus = 2))

	 begin
	 /* Either we are at the end of the fetch or we are switching to
	 ** a different grantor. 
	 */

	       update #column_privileges 
	       set
			insertpriv 	= @public_insert,
			deletepriv 	= @public_delete,
	        	selectpriv 	= @public_select,
			updatepriv 	= @public_update,
			referencepriv 	= @public_reference
		from #column_privileges cp
	 	where (cp.grantor = @prev_grantor) and
	       	      (not EXISTS (select * 
			    	   from #useful_groups ug
			    	   where ug.grp_id = cp.grantee_gid))

         end
    end


    close grp_cursor


    /* 
    ** At this stage, we have populated the #column_privileges table with
    ** all the inherited privileges
    */

    
    /* 
    ** Now we will go through each user grant or revoke in table #sysprotects
    ** and update the privileges in #column_privileges table
    */
    open user_protect

    fetch user_protect into @grantee, @action, @protecttype, @columns, @grantor

    while (@@sqlstatus != 2)
    begin
	/*
	** In this loop, we can find grant row, revoke row or grant with grant option
	** row. We use protecttype to figure that. If it is grant, then the user specific
	** privileges are added to the user's inherited privileges. If it is a revoke,
	** then the revoked privileges are subtracted from the inherited privileges. If
	** it is a grant with grant option, we just store it as is because privileges can
	** only be granted with grant option to individual users
	*/

	/* 
	** for select action
	*/
	if (@action = @select_action)
	begin
	     /* get the inherited select privilege */
	     select @inherit_select = selectpriv
	     from   #column_privileges
	     where  (grantee = @grantee) and
		    (grantor = @grantor)

	     if (@protecttype = @grant_type)
	     /* the grantee has a individual grant */
		exec sybsystemprocs.dbo.syb_aux_privunion @inherit_select, @columns, 
						  @col_count, @inherit_select output

	     else 
		if (@protecttype = @revoke_type)
		/* it is a revoke row */
		     exec sybsystemprocs.dbo.syb_aux_privexor @inherit_select, @columns, 
						      @col_count, @inherit_select output

	        else
		     /* it is a grant with grant option */

		     select @select_go = @columns

  	     /* modify the privileges for this user */
	
	     if ((@protecttype = @revoke_type) or (@protecttype = @grant_type))
	     begin
	     	  update #column_privileges
	     	  set selectpriv = @inherit_select
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end
	     else
	     begin

	     	  update #column_privileges
	     	  set select_go = @select_go
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end
	end

	/*
	** update action
	*/
	if (@action = @update_action)
	begin
	     /* find out the inherited update privilege */
	     select @inherit_update = updatepriv
	     from   #column_privileges
	     where  (grantee = @grantee) and
		    (grantor = @grantor)

		
	     if (@protecttype = @grant_type)
	     /* user has an individual grant */
		exec sybsystemprocs.dbo.syb_aux_privunion @inherit_update, @columns, 
						  @col_count, @inherit_update output

	     else 
		if (@protecttype = @revoke_type)
		     exec sybsystemprocs.dbo.syb_aux_privexor @inherit_update, @columns, 
						      @col_count, @inherit_update output

	        else
		     /* it is a grant with grant option */
		     select @update_go = @columns


  	     /* modify the privileges for this user */
	
	     if ((@protecttype = @revoke_type) or (@protecttype = @grant_type))
	     begin
	     	  update #column_privileges
	     	  set updatepriv = @inherit_update
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end
	     else
	     begin
	     	  update #column_privileges
	     	  set update_go = @update_go
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end
	end

	/* it is the reference privilege */
	if (@action = @reference_action)
	begin
	     select @inherit_reference = referencepriv
	     from   #column_privileges
	     where  (grantee = @grantee) and
		    (grantor = @grantor)


	     if (@protecttype = @grant_type)
	     /* the grantee has a individual grant */
		exec sybsystemprocs.dbo.syb_aux_privunion @inherit_reference, @columns, 
						  @col_count, @inherit_reference output

	     else 
		if (@protecttype = @revoke_type)
		/* it is a revoke row */
		     exec sybsystemprocs.dbo.syb_aux_privexor @inherit_reference, @columns, 
						      @col_count, @inherit_reference output

	        else
		     /* it is a grant with grant option */
		     select @reference_go = @columns


  	     /* modify the privileges for this user */
	
	     if ((@protecttype = @revoke_type) or (@protecttype = @grant_type))
	     begin
	     	  update #column_privileges
	     	  set referencepriv = @inherit_reference
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end
	     else
	     begin
	     	  update #column_privileges
	     	  set reference_go = @reference_go
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end

	end

	/*
	** insert action
	*/

	if (@action = @insert_action)
	begin
	     if (@protecttype = @grant_type)
		   select @inherit_insert = 1
	     else
		 if (@protecttype = @revoke_type)
		      select @inherit_insert = 0
		 else
		      select @insert_go = 1

	     
  	     /* modify the privileges for this user */
	
	     if ((@protecttype = @revoke_type) or (@protecttype = @grant_type))
	     begin
	     	  update #column_privileges
	     	  set insertpriv = @inherit_insert
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end
	     else
	     begin
	     	  update #column_privileges
	     	  set insert_go = @insert_go
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end

	end

	/* 
	** delete action
	*/

	if (@action = @delete_action)
	begin
	     if (@protecttype = @grant_type)
		   select @inherit_delete = 1
	     else
		 if (@protecttype = @revoke_type)
		      select @inherit_delete = 0
		 else
		      select @delete_go = 1

	     
  	     /* modify the privileges for this user */
	
	     if ((@protecttype = @revoke_type) or (@protecttype = @grant_type))
	     begin
	     	  update #column_privileges
	     	  set deletepriv = @inherit_delete
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end
	     else
	     begin
	     	  update #column_privileges
	     	  set delete_go = @delete_go
	     	  where (grantor = @grantor) and
		        (grantee = @grantee)
	     end

	end

        fetch user_protect into @grantee, @action, @protecttype, @columns, @grantor
    end

    close user_protect

open col_priv_cursor
fetch col_priv_cursor into @grantor, @grantee, @inherit_insert, @insert_go,
	                 @inherit_delete, @delete_go, @inherit_select, @select_go,
			 @inherit_update, @update_go, @inherit_reference, @reference_go

while (@@sqlstatus != 2)
begin

      /* 
      ** name of the grantor
      */
      select @grantor_name = name 
      from   sysusers
      where  uid = @grantor


      /*
      ** name of the grantee
      */

      select @grantee_name = name
      from   sysusers
      where  uid = @grantee


      if (@column_name = '%')
      /* 
      ** we need to print the privilege information for all columns of the table
      */
      begin
	    select @col_pos = 1

 	    while (@col_pos <= @col_count)
	    begin

		 select @curr_column = col_name (@tab_id, @col_pos)

  	         /* 
	         ** check for insert privileges
	         */
	         exec sybsystemprocs.dbo.syb_aux_printprivs 
			@calledfrom_colpriv, @col_pos, @inherit_insert, @insert_go, 0x00, 0x00, 0, 
				@grantable output, @is_printable output

	         if (@is_printable = 1)
		 begin
		        insert into #results_table
		                values (@table_qualifier, @table_owner, @table_name, @curr_column,
				@grantor_name, @grantee_name, 'INSERT', @grantable)
		 end

	         /* 
	         ** check for select privileges
	         */
	         exec sybsystemprocs.dbo.syb_aux_printprivs 
			@calledfrom_colpriv, @col_pos, 0, 0, @inherit_select, @select_go, 1, 
			@grantable output, @is_printable output

	         if (@is_printable = 1)
		 begin
		        insert into #results_table
		   		values (@table_qualifier, @table_owner, @table_name, @curr_column,
				@grantor_name, @grantee_name, 'SELECT', @grantable)
		 end
	         /* 
	         ** check for update privileges
	         */
	         exec sybsystemprocs.dbo.syb_aux_printprivs 
			@calledfrom_colpriv, @col_pos, 0, 0, @inherit_update, @update_go, 1, 
			@grantable output, @is_printable output

	         if (@is_printable = 1)
		 begin
		 	 insert into #results_table
		   		values (@table_qualifier, @table_owner, @table_name, @curr_column,
				@grantor_name, @grantee_name, 'UPDATE', @grantable)
		 end
	         /*
	         ** check for reference privs
	   	 */

	 	exec sybsystemprocs.dbo.syb_aux_printprivs 
		        @calledfrom_colpriv, @col_pos, 0, 0, @inherit_reference, @reference_go, 1, 
				@grantable output, @is_printable output

	    	if (@is_printable = 1)
		begin
			insert into #results_table
			        values (@table_qualifier, @table_owner, @table_name, @curr_column,
				@grantor_name, @grantee_name, 'REFERENCE', @grantable)
		end

		select @col_pos = @col_pos + 1
	    end
      end
      else
      begin

      /* 
      ** At this point, we are either printing privilege information for a
      ** a specific column or for table_privileges
      */

	    select @col_pos = 0

	    if (@calledfrom_colpriv = 1)
	    begin
	    /* 
	    ** find the column position
	    */
	         select @col_pos = colid
	         from syscolumns
	         where (id = @tab_id) and
		       (name = @column_name)
	    end

	    /* 
	    ** check for insert privileges
	    */
	    exec sybsystemprocs.dbo.syb_aux_printprivs 
			@calledfrom_colpriv, @col_pos, @inherit_insert, @insert_go, 0x00, 0x00, 0, 
				@grantable output, @is_printable output

	    if (@is_printable = 1)
	    begin
		  insert into #results_table
		       values (@table_qualifier, @table_owner, @table_name, @column_name,
				@grantor_name, @grantee_name, 'INSERT', @grantable)
	    end

	    /* 
	    ** check for delete privileges
	    */

	    if (@calledfrom_colpriv = 0)
	    /* delete privilge need only be printed if called from sp_table_privileges */
	    begin
	 	    exec sybsystemprocs.dbo.syb_aux_printprivs 
		         @calledfrom_colpriv, @col_pos, @inherit_delete, @delete_go, 0x00, 0x00, 0, 
				@grantable output, @is_printable output

	    	    if (@is_printable = 1)
		    begin
		  	insert into #results_table
			        values (@table_qualifier, @table_owner, @table_name, @column_name,
				@grantor_name, @grantee_name, 'DELETE', @grantable)
		    end
	    end

	    /* 
	    ** check for select privileges
	    */
	    exec sybsystemprocs.dbo.syb_aux_printprivs 
			@calledfrom_colpriv, @col_pos, 0, 0, @inherit_select, @select_go, 1, 
			@grantable output, @is_printable output


	    if (@is_printable = 1)
	    begin
		  insert into #results_table
		  	 values (@table_qualifier, @table_owner, @table_name, @column_name,
				@grantor_name, @grantee_name, 'SELECT', @grantable)
	    end
	    /* 
	    ** check for update privileges
	    */
	    exec sybsystemprocs.dbo.syb_aux_printprivs 
			@calledfrom_colpriv, @col_pos, 0, 0, @inherit_update, @update_go, 1, 
			@grantable output, @is_printable output

	    if (@is_printable = 1)
	    begin
		  insert into #results_table
		   	values (@table_qualifier, @table_owner, @table_name, @column_name,
				@grantor_name, @grantee_name, 'UPDATE', @grantable)
	    end
	    /*
	    ** check for reference privs
	    */
	    if (@calledfrom_colpriv = 1)
	    /* reference privilge need only be printed if called from sp_column_privileges */
	    begin
	 	    exec sybsystemprocs.dbo.syb_aux_printprivs 
			 @calledfrom_colpriv, @col_pos, 0, 0, @inherit_reference, @reference_go, 1, 
				@grantable output, @is_printable output

	    	    if (@is_printable = 1)
		    begin
		  	insert into #results_table
			        values (@table_qualifier, @table_owner, @table_name, @column_name,
				@grantor_name, @grantee_name, 'REFERENCE', @grantable)
		    end
	    end

      end


      fetch col_priv_cursor into @grantor, @grantee, @inherit_insert, @insert_go,
	                 @inherit_delete, @delete_go, @inherit_select, @select_go,
			 @inherit_update, @update_go, @inherit_reference, @reference_go
end

    
/*
** Outputting the results table
*/

if (@calledfrom_colpriv = 1)
	select *
	from #results_table

else
        select table_qualifier, table_owner, table_name, grantor, grantee,
	       privilege, is_grantable
	from #results_table

close col_priv_cursor

    drop table #column_privileges
    drop table #distinct_grantors
    drop table #sysprotects
    drop table #useful_groups
    drop table #results_table
go
exec sp_procxmode 'sp_aux_computeprivs', 'anymode'
go
grant execute on sp_aux_computeprivs to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_column_privileges')
begin
	drop procedure sp_column_privileges
end
go
print "Installing sp_column_privileges"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure sp_column_privileges ( 
                        @table_name  varchar(32),
                        @table_owner varchar(32) = null,
                        @table_qualifier varchar(32)= null,
                        @column_name varchar(32) = null)

as        

    declare @owner_id    		int
    declare @full_table_name    	char(70)
    declare @tab_id 			int	    /* object id of the table specified */
    declare @msg			varchar (255)

    set nocount on
    /*
    ** set the transaction isolation level
    */
    if @@trancount = 0
    begin
	   set chained off
    end
    else
    begin
	 /* we are inside a transaction. catalog procedure sp_column privileges
	 ** can't be run inside a transaction 
	 */
         exec sp_getmessage 18040, @msg  output
	 raiserror 18040, @msg, "sp_column_privileges"
	 return (1)
    end

    set transaction isolation level 1

    /*
    **  Check to see that the table is qualified with database name
    */
    if @table_name like "%.%.%" 
    begin
	/* 18021, "Object name can only be qualified with owner name" */
	exec sp_getmessage 18021, @msg out
	print @msg
	return (1)
    end

    /*  If this is a temporary table; object does not belong to 
    **  this database; (we should be in the tempdb)
    */
    if (@table_name like "#%" and db_name() != "tempdb")
    begin
	/* 
	** 17676, "This may be a temporary object. Please execute 
	** procedure from tempdb."
	*/
	exec sp_getmessage 17676, @msg out
	print @msg
	return (1)
    end

    /*
    ** The table_qualifier should be same as the database name. Do the sanity check
    ** if it is specified
    */
    if (@table_qualifier is null) or (@table_qualifier = '')
	/* set the table qualifier name */
	select @table_qualifier = db_name ()
    else
    begin
        if db_name() != @table_qualifier
        begin
	     exec sp_getmessage 18039, @msg out
	     print @msg
	     return (1)
	end
    end
   
    /* 
    ** if the table owner is not specified, it will be taken as the id of the
    ** user executing this procedure. Otherwise find the explicit table name prefixed
    ** by the owner id
    */
    if (@table_owner is null) or (@table_owner = '')
	        select @full_table_name = @table_name
    else
    begin
	if (@table_name like "%.%") and
	    substring (@table_name, 1, charindex(".", @table_name) -1) != @table_owner
	begin
 	/* 18011, Object name must be qualified with the owner name * */
		exec sp_getmessage 18011, @msg out
		print @msg
		return (1)
	end
	
	if not (@table_name like "%.%")
        	select @full_table_name = @table_owner + '.' + @table_name
	else
	        select @full_table_name = @table_name

    end

    /* 
    ** check to see if the specified table exists or not
    */

    select @tab_id = object_id(@full_table_name)
    if (@tab_id is null)
    begin
	exec sp_getmessage 17492, @msg out
	print @msg
	return (1)
    end


    /*
    ** check to see if the @tab_id indeeed represents a table or a view
    */

    if not exists (select * 
                  from   sysobjects
                  where (@tab_id = id) and
	                ((type = 'U') or
                        (type = 'S') or
		        (type = 'V')))
    begin
	exec sp_getmessage 17492, @msg out
	print @msg
	return (1)
    end
 

    /*
    ** if the column name is not specified, set the column name to wild character such
    ** it matches all the columns in the table
    */
    if @column_name is null
        select @column_name = '%'

    else
    begin
         /*
	 ** check to see if the specified column is indeed a column belonging
	 ** to the table
	 */
         if not exists (select * 
                        from syscolumns
			where (id = @tab_id) and
			      (name = @column_name))
	 begin
		exec sp_getmessage 17563, @msg out
		print @msg, @column_name
		return (1)
         end
    end


   /* 
   ** compute the table owner id
   */

    select @owner_id = uid
    from   sysobjects
    where  id = @tab_id



   /*
   ** get table owner name
   */

    select @table_owner = name 
    from sysusers 
    where uid = @owner_id


    exec sp_aux_computeprivs @table_name, @table_owner, @table_qualifier, 
			     @column_name, 1, @tab_id

    set nocount off 	
    return (0)

go
exec sp_procxmode 'sp_column_privileges', 'anymode'
go
grant execute on sp_column_privileges to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_table_privileges')
begin
	drop procedure sp_table_privileges
end
go
print "Installing sp_table_privileges"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure sp_table_privileges ( 
                        @table_name  varchar(32),
                        @table_owner varchar(32) = null,
                        @table_qualifier varchar(32)= null)
as        
 
    declare @owner_id    		int
    declare @full_table_name    	char(70)
    declare @tab_id 			int	    /* object id of the table specified */

    declare @msg			varchar (255)

    set nocount on
    /*
    ** set the transaction isolation level
    */
    if @@trancount = 0
    begin
	   set chained off
    end
    else
    begin
	 /* we are inside a transaction. catalog procedure sp_column privileges
	 ** can't be run inside a transaction 
	 */
         exec sp_getmessage 18040, @msg  output
	 raiserror 18040, @msg, "sp_column_privileges"
	 return (1)
    end

    set transaction isolation level 1

    /*
    **  Check to see that the table is qualified with the database name
    */
    if @table_name like "%.%.%"
    begin
	/* 18021, "Object name can only be qualified with owner name" */
	exec sp_getmessage 18021, @msg out
	print @msg
	return (1)
    end

    /*  If this is a temporary table; object does not belong to 
    **  this database; (we should be in the tempdb)
    */
    if (@table_name like "#%" and db_name() != "tempdb")
    begin
	/* 
	** 17676, "This may be a temporary object. Please execute 
	** procedure from tempdb."
	*/
	exec sp_getmessage 17676, @msg out
	print @msg
	return (1)
    end


    /*
    ** The table_qualifier should be same as the database name. Do the sanity check
    ** if it is specified
    */
    if (@table_qualifier is null) or (@table_qualifier = '')
	/* set the table qualifier name */
	select @table_qualifier = db_name ()
    else
    begin
        if db_name() != @table_qualifier
        begin
	     exec sp_getmessage 18039, @msg out
	     print @msg
	     return (1)
	end
    end
   
    /* 
    ** if the table owner is not specified, it will be taken as the id of the
    ** user executing this procedure. Otherwise find the explicit table name prefixed
    ** by the owner id
    */
    if (@table_owner is null) or (@table_owner = '')
        select @full_table_name = @table_name
    else
    begin
	if (@table_name like "%.%") and
	    substring (@table_name, 1, charindex(".", @table_name) -1) != @table_owner
	begin
 	/* 18011, Object name must be qualified with the owner name * */
		exec sp_getmessage 18011, @msg out
		print @msg
		return (1)
	end
	
	if not (@table_name like "%.%")
        	select @full_table_name = @table_owner + '.' + @table_name
	else
	        select @full_table_name = @table_name
    end

    /* 
    ** check to see if the specified table exists or not
    */

    select @tab_id = object_id(@full_table_name)
    if (@tab_id is null)
    begin
	exec sp_getmessage 17492, @msg out
	print @msg
	return (1)
    end


    /*
    ** check to see if the @tab_id indeeed represents a table or a view
    */

    if not exists (select * 
                  from   sysobjects
                  where (@tab_id = id) and
	                ((type = 'U') or
                        (type = 'S') or
		        (type = 'V')))
    begin
	exec sp_getmessage 17492, @msg out
	print @msg
	return (1)
    end

   /* 
   ** compute the table owner id
   */

    select @owner_id = uid
    from   sysobjects
    where  id = @tab_id



   /*
   ** get table owner name
   */

    select @table_owner = name 
    from sysusers 
    where uid = @owner_id


    exec sp_aux_computeprivs @table_name, @table_owner, @table_qualifier, 
			     NULL, 0, @tab_id

    set nocount off 	
    return (0)

go
exec sp_procxmode 'sp_table_privileges', 'anymode'
go
grant execute on sp_table_privileges to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_changegroup')
begin
	drop procedure sp_changegroup
end
go
print "Installing sp_changegroup"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/changegroup */

/*
** Messages for "sp_changegroup"        17370
**
** 17333, "No such group exists."
**      (is now: "No group with the specified name exists.")
** 17232, "No such user exists."
**      (is now: "No user with the specified name exists in the current
** database.")
** 17370, "Group changed."
*/

create procedure sp_changegroup
@grpname varchar(30),			/* group name */
@username varchar(30)			/* user name to add to group */
as

declare @gid smallint			/* group id */
declare @uid smallint			/* user id */
declare @msg varchar(250)
declare @id  int			/* object id */
declare @grantee smallint		/* grantee */
declare @action	tinyint			/* action (i.e select, insert) */
declare @protecttype tinyint		/* grant/revoke/option */
declare @columns varbinary (32)		/* column priv bit map */
declare @grantor smallint		/* grantor */
declare @gcolumns varbinary (32)        /* group column privileges */
declare @pcolumns varbinary (32)	/* public column privileges */
declare @aggrprivs tinyint		/* object level privs of group and public */
declare @aggrcolumns varbinary (32)	/* aggregate of group and public privileges */
declare @col_count smallint


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
	return(1)

/*
**  See if the group name exists.
*/
select @gid = uid
	from sysusers
where name = @grpname
	and (uid > 16383 or uid = 0)
	and not exists (select name from master.dbo.syssrvroles
			where name = @grpname)

/*
**  If no such group, quit.
**  User ids range from -16383 to +16383 and group ids are > 16383 or = 0.
*/
if @gid is NULL
begin
	/*
	** 17333, "No such group exists."
	*/
	exec sp_getmessage 17333, @msg output
        print @msg
	return (1)
end

/*
**  See if the user name exists.
*/
select @uid = uid
	from sysusers
where name = @username
	and (uid <= 16383 and uid != 0)

/*
**  If no such user in the database, quit.
*/
if @uid is NULL
begin

	/*
	** 17232, "No such user exists."
	*/
	exec sp_getmessage 17232, @msg output
        print @msg
	return (1)
end

/*
** At this stage everything is consistent with respect to parameters.
** Now we need to update the GRANTS/REVOKES to the user with respect to
** the new group
*/

begin transaction



/* 
** cursor to find tuples in sysprotect for which grantee is @uid 
*/
declare priv_curs cursor for 
	select id, uid, action, protecttype, columns, grantor
	from sysprotects
	where uid = @uid
	for update

/*
** open the cursor and start fetching from it
*/

open priv_curs

fetch priv_curs into @id, @grantee, @action, @protecttype, @columns, @grantor

/* loop for all qualifying rows */
while (@@sqlstatus != 2)
begin
     if (@@sqlstatus = 1)
     begin
	 /* error in fetching from the cursor */
	exec sp_getmessage 17333, @msg output
        print @msg
	rollback transaction
	return (1)
     end

     /*
     ** 193 is SELECT, 197 is UPDATE, 151 is REFERENCES. These are column
     ** level privileges 
     */
     if (((@action != 193) and (@action != 197)) and (@action != 151))
     begin
	  /*
	  ** these are object level privileges 
	  ** Note that grant with grant can't be given to group/PUBLIC thus
	  ** not considered  
          */
	  if (@protecttype = 1)
	  begin
	       /* it is a grant row  */
	       /* initialize aggregate privs */
	       select @aggrprivs = 0

	       /*
	       ** check if this grant is available to public
               */
	       if (exists (select * from sysprotects
		           where (id = @id) and
				 (uid = 0) and
				 (action = @action) and
				 (protecttype = @protecttype) and
				 (grantor = @grantor)))
	       begin
		     select @aggrprivs = 1		    
	       end

	       
	       if (@aggrprivs = 1)
	       begin
		    /* the grant of this privilege is available thru PUBLIC
		       check if there is a revoke to the new group */
	            if (exists (select * from sysprotects
		                where (id = @id) and
				      (uid = @gid) and
				      (action = @action) and
				      (protecttype = 2) and
				      (grantor = @grantor)))
		    begin
			  /* the revoke from group nullifies the grant from 
			     PUBLIC */
			  select @aggrprivs = 0
		    end
	       end
	       else
	       begin
		    /* the privilege was not available thru PUBLIC, check if
		       it is available thru group */
	            if (exists (select * from sysprotects
		                where (id = @id) and
				      (uid = @gid) and
				      (action = @action) and
				      (protecttype = 1) and
				      (grantor = @grantor)))
		    begin
			 /* the privilege is inherited from the group */
			 select @aggrprivs = 1
		    end
	       end


	       /* delete the grant to the user, if inherited due to the 
		  membership in the group or public */

	       if (@aggrprivs = 1)
	       begin
		    delete from sysprotects where current of priv_curs
	       end   
	
	  end
	  else if (@protecttype = 2)
	  begin
	      /* it is a revoke */
	       if ((exists (select * from sysprotects
		           where (id = @id) and
			 	 (uid = @gid) and
				 (action = @action) and
				 (protecttype = @protecttype) and
				 (grantor = @grantor)))
	          or 
		  (not exists (select * from sysprotects
			   where (id = @id) and
				 (uid = @gid or uid = 0) and
				 (action = @action) and
				 (protecttype = 1) and	
				 (grantor = @grantor))))
	       begin
		    /* the privilege is already revoked from the group or there is no
		       explicit grant of this privilege to either group or public, so
		       this revoke row not needed */
		    delete from sysprotects where current of priv_curs
		    
	       end
	  end
      end
      else
      begin
	   /* column level privileges */
           /* initialize column privilege map for public and group */
	   select @pcolumns = 0x00
	   select @gcolumns = 0x00

           /* get the number of columns in this table. It is only used for
           ** column level privileges 
	   */
           select @col_count = count (*)
           from syscolumns
           where id = @id

	   /* find the column level privileges to PUBLIC */
	   if (exists (select * from sysprotects
		       where (id = @id) and
			     (uid = 0) and
			     (action = @action) and
			     (protecttype = 1) and
		 	     (grantor = @grantor)))
	   begin
		select @pcolumns = columns from sysprotects
		where (id = @id) and
		      (uid = 0) and
		      (action = @action) and
		      (protecttype = 1) and
		      (grantor = @grantor)
	   end

	   /* find the column level privilege to the new GROUP */
	   if (exists (select * from sysprotects
		       where (id = @id) and
			     (uid = @gid) and
			     (action = @action) and
			     (protecttype = 1) and
			     (grantor = @grantor)))
	   begin
		select @gcolumns = columns from sysprotects
		where (id = @id) and
		      (uid = @gid) and
		      (action = @action) and
		      (protecttype = 1) and
		      (grantor = @grantor)
	   end
	      
	  /* find the union of column privileges from public as
	  ** new group  
	  */
	  exec sybsystemprocs.dbo.syb_aux_privunion @pcolumns, @gcolumns, @col_count, @aggrcolumns output

	  /* find if there is a revoke row for the above privilege 
	  ** in the group 
          */
	  select @gcolumns = 0x00
          if (exists (select * from sysprotects
	  	      where (id = @id) and
			    (uid = @gid) and
			    (action = @action) and
			    (protecttype = 2) and
			    (grantor = @grantor)))
	  begin
	       select @gcolumns = columns from sysprotects
	       where (id = @id) and
		     (uid = @gid) and
		     (action = @action) and
		     (protecttype = 2) and
		     (grantor = @grantor)

	  end

          /* subtract the revoke to columns from the group. In order to subtract,
	     exor operation will do as the revoke column bit can only be for columns
	     for which the user has inherited grant */

          exec sybsystemprocs.dbo.syb_aux_privexor @aggrcolumns, @gcolumns, @col_count, @aggrcolumns output

          /* at this stage, aggrcolumns contains the effective column privileges 
	     that are inherited */

	  if (@protecttype = 1)
	  begin
	       /* we encountered an explicit user specific grant row */
	       exec sybsystemprocs.dbo.syb_aux_privnots @aggrcolumns, @col_count, @aggrcolumns output

	       exec sybsystemprocs.dbo.syb_aux_privsand @columns, @aggrcolumns, @col_count, @columns output


	       if (@columns = 0x00)
	       begin
		     /* delete the grant row if no column is left. This implies that
			all explicit user grants were also inherited due to the user's
			membership in the group or PUBLIC */
		     delete sysprotects where current of priv_curs
	       end
	       else
	       begin
		    /* update the list of columns in the grant */
		    update sysprotects set columns = @columns
		    where current of priv_curs
	       end
	  end
	  else if (@protecttype = 2)
	  begin
	       /* it is a revoke row */
	       exec sybsystemprocs.dbo.syb_aux_privsand @columns, @aggrcolumns, @col_count, @columns output
	       /* We only keep those revoke bits for which there is an inherited
		  grant from the user's membership in the group or PUBLIC */
	       if (@columns = 0x00)
	       begin
		     /* delete the revoke row if no column is left */
		     delete sysprotects where current of priv_curs
	       end
	       else
	       begin
		    /* update the list of columns in the revoke */
		    update sysprotects set columns = @columns
		    where current of priv_curs
	       end

	  end
      end
      /*
      ** get the next qualifying tuple 
      */
      fetch priv_curs into @id, @grantee, @action, @protecttype, @columns, @grantor
end	
	
/*
**  Everything is consistent so change the group.
*/
update sysusers
	set gid = @gid
		from sysusers
	where uid = @uid


commit transaction

/*
**  We need to invalidate the protection cache since objects have
**  changed ownership.  This command will invalidate the current
**  protection cache so when protections are checked the new and
**  correct protections will be used.
*/
grant all to null
/*
** 17370, "Group changed."
*/
exec sp_getmessage 17370, @msg output
print @msg
return (0)
go
exec sp_procxmode 'sp_changegroup', 'anymode'
go
grant execute on sp_changegroup to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_checknames')
begin
	drop procedure sp_checknames
end
go
print "Installing sp_checknames"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/checknames */


create procedure sp_checknames
@mode varchar(20) = NULL		/* mode of operation; e.g. 'silent' */
as

declare @msilent	int		/* set to 1 if 'silent' mode is on */
declare @ret_val	int		/* set to 1 if we find funny char */
declare @codepoint	tinyint
declare @dbname		varchar(30)	/* holds database name */
declare @msg		varchar(255)	/* used for messages to user */
declare @pat		varchar(255)	/* holds the pattern to search for */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

if (@mode like '%help%')
begin
	print 'sp_checknames is used to search for non 7-bit ASCII characters'
	print 'in several important columns of system tables.  The following'
	print 'columns are searched:'
	print ' '
	print '    In "master":'
	print '        sysdatabases.name'
	print '        sysdevices.name'
	print '        syslogins.name'
	print '        syslogins.dbname'
	print '        syslogins.password'
	print '        sysremotelogins.remoteusername'
	print '        sysservers.srvname'
	print '        sysservers.srvnetname'
	print ' '
	print '    In all databases:'
	print '        syscolumns.name'
	print '        sysindexes.name'
	print '        sysobjects.name'
	print '        syssegments.name'
	print '        systypes.name'
	print '        sysusers.name'
	print ' '

	return (0)
end

/*
**  First, initialize return value, and set up mode variables:
*/
select @ret_val = 0

if (@mode like '%silent%')
	select @msilent = 1
else
	select @msilent = 0


/*
**  Now, initialize the pattern string we will search for:
**	@pat contains the pattern "NOT IN THE RANGE OF all 7-bit ASCII
**	characters, except the right bracket "]".  (As of release 4.9.1,
**	it is not possible to represent the right bracket in the non-
**	inclusive matching pattern.)
*/
select @pat = '%[^- !"#$%&''()*+,./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\^_`abcdefghijklmnopqrstuvwxyz{|}~'

select @codepoint = 0
while (@codepoint < 32)
begin
	select @pat = @pat + char(@codepoint)
	select @codepoint = @codepoint + 1
end

select @pat = @pat + char(127) + ']%'


/*
**  Get the database name we are in:
*/
select @dbname = db_name()

if (@msilent = 0)
begin
	print ' '
	select @msg = 'Looking for non 7-bit ASCII characters in the system ' +
			'tables of database:  "' + @dbname + '"'
	print @msg
	print ' '
end


/*
**  Look through these only if in the master database:
*/
if (@dbname = 'master')
begin
    if exists (select name from master.dbo.sysdatabases
		    where name like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "sysdatabases.name"'
	print ' '
	print 'The following database names contain non 7-bit ASCII characters.'
	print 'If you wish to change their names, use "sp_renamedb":'
	print ' '
	select dbid,name from master.dbo.sysdatabases
			where name like @pat
    end

    if exists (select name from master.dbo.sysdevices
		    where name like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "sysdevices.name"'
	print ' '
	print 'The following device names contain non 7-bit ASCII characters.'
	print 'If you wish to change their names, use "UPDATE":'
        print ' '
	select name from master.dbo.sysdevices
			where name like @pat
    end

    if exists (select name from master.dbo.syslogins
		    where name like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "syslogins.name"'
        print ' '
	print 'The following login names contain non 7-bit ASCII characters.'
	print 'If you wish to change these names, use "sp_droplogin" and'
	print '"sp_addlogin":'
        print ' '
	select suid,name from master.dbo.syslogins
			where name like @pat
    end

    if exists (select dbname from master.dbo.syslogins
		    where dbname like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "syslogins.dbname"'
	print ' '
	print 'The following logins have default database names that contain'
	print 'non 7-bit ASCII characters.  If you wish to change them use'
	print '"sp_defaultdb":'
        print ' '
	select suid,name,dbname from master.dbo.syslogins
			where dbname like @pat
    end

/*
**  @pat contains the pattern "NOT IN THE RANGE OF all 7-bit ASCII characters,
**  except the right bracket ("]").  Thus, if a password contains the right
**  bracket character, this non-inclusive matching pattern will not work, and
**  sp_checknames will think the password contains non 7-bit ASCII characters.
*/
    if exists (select password from master.dbo.syslogins
		    where password like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "syslogins.password"'
	print ' '
	print 'The following logins have passwords that contain non 7-bit'
	print 'ASCII characters.  If you wish to change them use "sp_password";'
	print 'Remember, only the sa and the login itself may examine or change'
	print 'the syslogins.password column:'
        print ' '
	select suid,name from master.dbo.syslogins
			where password like @pat
    end

    if exists (select remoteusername from master.dbo.sysremotelogins
		    where remoteusername like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "sysremotelogins.remoteusername"'
        print ' '
	print 'The following remote login names contain non 7-bit ASCII'
	print 'characters.  If you wish to change these names, use'
	print '"sp_dropremotelogin" and "sp_addremotelogin":'
        print ' '
	select remoteserverid,remoteusername from master.dbo.sysremotelogins
			where remoteusername like @pat
    end

    if exists (select srvname from master.dbo.sysservers
		    where srvname like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "sysservers.srvname"'
        print ' '
	print 'The following server names contain non 7-bit ASCII characters.'
	print 'If you wish to change their names, use "sp_dropserver" and'
	print '"sp_addserver":'
        print ' '
	select srvid,srvname from master.dbo.sysservers
			where srvname like @pat
    end

    if exists (select srvnetname from master.dbo.sysservers
		    where srvnetname like @pat)
    begin
	if (@msilent = 1)
	    return (1)

	select @ret_val = 1
	print ' '
	print '==============================================================='
	print 'Table.Column name:  "sysservers.srvnetname"'
        print ' '
	print 'The following servers have "interface file" names that contain'
	print 'non 7-bit ASCII characters.  If you wish to change these names,'
	print 'use "UPDATE":'
        print ' '
	select srvid,srvname,srvnetname from master.dbo.sysservers
			where srvnetname like @pat
    end

end


/*
**  For *ALL* databases, we want to look through these:
*/
if exists (select name from dbo.syscolumns
	    where name like @pat)
begin
    if (@msilent = 1)
	return (1)

    select @ret_val = 1
    print ' '
    print '==============================================================='
    print 'Table.Column name:  "syscolumns.name"'
    print ' '
    print 'The following column and parameter names contain non 7-bit ASCII'
    print 'characters.  If you wish to change these names, use "sp_rename":'
    print ' '
    select objname=o.name,colname=c.name from dbo.syscolumns c, dbo.sysobjects o
		where c.name like @pat and o.id = c.id
end

if exists (select name from dbo.sysindexes
            where name like @pat
                  and indid > 0)
begin
    if (@msilent = 1)
	return (1)

    select @ret_val = 1
    print ' '
    print '==============================================================='
    print 'Table.Column name:  "sysindexes.name"'
    print ' '
    print 'The following index names contain non 7-bit ASCII characters.'
    print 'If you wish to change these names, use "UPDATE":'
    print ' '
    select id,indid,name from dbo.sysindexes
		where name like @pat
end

if exists (select name from dbo.sysobjects
	    where name like @pat)
begin
    if (@msilent = 1)
	return (1)

    select @ret_val = 1
    print ' '
    print '==============================================================='
    print 'Table.Column name:  "sysobjects.name"'
    print ' '
    print 'The following object names contain non 7-bit ASCII characters.'
    print 'If you wish to change these names, use "sp_rename":'
    print ' '
    select owner=u.name,o.name from dbo.sysobjects o,dbo.sysusers u
		where o.name like @pat and o.uid=u.uid
end

if exists (select name from dbo.syssegments
	    where name like @pat)
begin
    if (@msilent = 1)
	return (1)

    select @ret_val = 1
    print ' '
    print '==============================================================='
    print 'Table.Column name:  "syssegments.name"'
    print ' '
    print 'The following segment names contain non 7-bit ASCII characters.'
    print 'If you wish to change these names, use "UPDATE":'
    print ' '
    select segment,name from dbo.syssegments
		where name like @pat
end

if exists (select name from dbo.systypes
	    where name like @pat)
begin
    if (@msilent = 1)
	return (1)

    select @ret_val = 1
    print ' '
    print '==============================================================='
    print 'Table.Column name:  "systypes.name"'
    print ' '
    print 'The following datatype names contain non 7-bit ASCII characters.'
    print 'If you wish to change these names, use "sp_rename":'
    print ' '
    select name from dbo.systypes
		where name like @pat
end

if exists (select name from dbo.sysusers
	    where name like @pat)
begin
    if (@msilent = 1)
	return (1)

    select @ret_val = 1
    print ' '
    print '==============================================================='
    print 'Table.Column name:  "sysusers.name"'
    print ' '
    print 'The following user or group names contain non 7-bit ASCII'
    print 'characters.  If you wish to change these names, use "UPDATE":'
    print ' '
    select suid,uid,name from dbo.sysusers
		where name like @pat
end

if (@ret_val = 0  and  @msilent = 0)
begin
    select @msg = 'Good news!  Database "' + @dbname + '" has no obj/user/etc.'
    print @msg
    print 'names that contain non 7-bit ASCII characters.'
end

return (@ret_val)
go
exec sp_procxmode 'sp_checknames', 'anymode'
go
grant execute on sp_checknames to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_commonkey')
begin
	drop procedure sp_commonkey
end
go
print "Installing sp_commonkey"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/commonkey */

/*
** Messages for "sp_commonkey"          17390
**
** 17390, "Table or view name must be in 'current' database."
** 17391, "First table in the common key doesn't exist."
** 17392, "Second table in the common key doesn't exist."
** 17393, "Only the table owner may define its common keys."
** 17394, "The tables have no such first column or the columns are of different types."                     
** 17395, "The tables have no such second column or the columns are of different types."                    
** 17396, "The tables have no such third column or the columns are of different types."                     
** 17397, "The tables have no such fourth column or the columns are of different types."
** 17398, "The tables have no such fifth column or the columns are of different types."
** 17399, "The tables have no such sixth column or the columns are of different types."
** 17400, "The tables have no such seventh column or the columns are of different types."
** 17401, "The tables have no such eighth column or the columns are of different types."
** 17402, "New common key added."
*/


/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_commonkey 
@tabaname  varchar(92),		/* name of first table in the key */
@tabbname varchar(92),		/* name of second table in the key */
@col1a     varchar(30), 	/* first column name of first table */
@col1b     varchar(30), 	/* first column name of second table */
@col2a     varchar(30) = NULL,
@col2b     varchar(30) = NULL,
@col3a     varchar(30) = NULL,
@col3b     varchar(30) = NULL,
@col4a     varchar(30) = NULL,
@col4b     varchar(30) = NULL,
@col5a     varchar(30) = NULL,
@col5b     varchar(30) = NULL,
@col6a     varchar(30) = NULL,
@col6b     varchar(30) = NULL,
@col7a     varchar(30) = NULL,
@col7b     varchar(30) = NULL,
@col8a     varchar(30) = NULL,
@col8b     varchar(30) = NULL
as

declare @uida smallint		/* owner of the first table */
declare @cnt    int		/* how many columns are in the key */
declare @msg    varchar(250)

declare @key1a int		/* colids of the first table */
declare @key2a int
declare @key3a int
declare @key4a int
declare @key5a int
declare @key6a int
declare @key7a int
declare @key8a int

declare @key1b int		/* colids of the second table */
declare @key2b int
declare @key3b int
declare @key4b int
declare @key5b int
declare @key6b int
declare @key7b int
declare @key8b int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see that the tabnames are local.
*/
if @tabaname like "%.%.%"
begin
	if substring(@tabaname, 1, charindex(".", @tabaname) - 1) != db_name()
	begin
		/*
		** 17390, "Table or view name must be in 'current' database."
		*/
		exec sp_getmessage 17390, @msg output
		print @msg
		return (1)
	end
end
if @tabbname like "%.%.%"
begin
	if substring(@tabbname, 1, charindex(".", @tabbname) - 1) != db_name()
	begin
		/*
		** 17390, "Table or view name must be in 'current' database."
		*/
		exec sp_getmessage 17390, @msg output
		print @msg
		return (1)
	end
end

/*
**  See if we can find the objects.  They must be a system table, user table,
**  or view.  The low 3 bits of sysobjects.sysstat indicate what the 
**  object type is -- it's more reliable than using sysobjects.type which
**  could change.
*/
if not exists (select *
	from sysobjects
		where id = object_id(@tabaname)
			and (sysstat & 7 = 1		/* system table */
				or sysstat & 7 = 2	/* view */
				or sysstat & 7 = 3))	/* user table */
/*
**  If either of the tables don't exist, quit.
*/
begin
	/*
	** 17391, "First table in the common key doesn't exist."
	*/
	exec sp_getmessage 17391, @msg output
	print @msg
    	return (1)
end 
if not exists (select id
	from sysobjects
		where id = object_id(@tabbname)
			and (sysstat & 7 = 1
				or sysstat & 7 = 2
				or sysstat & 7 = 3))
begin
	/*
	** 17392, "Second table in the common key doesn't exist."
	*/
	exec sp_getmessage 17392, @msg output
	print @msg
    	return (1)
end 

/*
**  Only the owner of the table can define it's common keys.
*/
select @uida = uid
	from sysobjects
		where id = object_id(@tabaname)
			and (sysstat & 7 = 1		/* system table */
				or sysstat & 7 = 2	/* view */
				or sysstat & 7 = 3)	/* user table */
if @uida != user_id()
begin
	/*
	** 17393, "Only the table owner may define its common keys."
	*/
	exec sp_getmessage 17393, @msg output
	print @msg
	return (1)
end

/*
**  Now check to see that the first key columns exist and have compatible types.
*/
select @cnt = 1, @key1a = a.colid, @key1b = b.colid
	from syscolumns a, syscolumns b, master.dbo.spt_values y,
		master.dbo.spt_values z
		where a.name = @col1a
			and a.id = object_id(@tabaname)
			and b.name = @col1b
			and b.id = object_id(@tabbname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number
if @key1a is NULL
begin
	/*
	** 17394, "The tables have no such first column or the columns are of different types."
	*/
	exec sp_getmessage 17394, @msg output
	print @msg
	return (1)
end

if @col2a is not NULL
begin
	select @cnt = @cnt + 1, @key2a = a.colid, @key2b = b.colid
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
			where a.name = @col2a
				and a.id = object_id(@tabaname)
				and b.name = @col2b
				and b.id = object_id(@tabbname)
				and y.type = "J"
				and a.type = y.low
				and z.type = "J"
				and b.type = z.low
				and y.number = z.number
	if @key2a is NULL
	begin
		/*
		** 17395, "The tables have no such second column or the columns are of different types."
		*/
		exec sp_getmessage 17395, @msg output
		print @msg
		return (1)
	end
end
else goto keys_ok

if @col3a is not NULL
begin
	select @cnt = @cnt + 1, @key3a = a.colid, @key3b = b.colid
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
			where a.name = @col3a
				and a.id = object_id(@tabaname)
				and b.name = @col3b
				and b.id = object_id(@tabbname)
				and y.type = "J"
				and a.type = y.low
				and z.type = "J"
				and b.type = z.low
				and y.number = z.number
	if @key3a is NULL
	begin
		/*
		** 17396, "The tables have no such third column or the columns are of different types."                     
		*/
		exec sp_getmessage 17396, @msg output
		print @msg
		return (1)
	end
end
else goto keys_ok

if @col4a is not NULL
begin
	select @cnt = @cnt + 1, @key4a = a.colid, @key4b = b.colid
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
			where a.name = @col4a
				and a.id = object_id(@tabaname)
				and b.name = @col4b
				and b.id = object_id(@tabbname)
				and y.type = "J"
				and a.type = y.low
				and z.type = "J"
				and b.type = z.low
				and y.number = z.number
	if @key4a is NULL
	begin
		/*
		** 17397, "The tables have no such fourth column or the columns are of different types."
		*/
		exec sp_getmessage 17397, @msg output
		print @msg
		return (1)
	end
end
else goto keys_ok

if @col5a is not NULL
begin
	select @cnt = @cnt + 1, @key5a = a.colid, @key5b = b.colid
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
			where a.name = @col5a
				and a.id = object_id(@tabaname)
				and b.name = @col5b
				and b.id = object_id(@tabbname)
				and y.type = "J"
				and a.type = y.low
				and z.type = "J"
				and b.type = z.low
				and y.number = z.number
	if @key5a is NULL
	begin
		/*
		** 17398, "The tables have no such fifth column or the columns are of different types."
		*/
		exec sp_getmessage 17398, @msg output
		print @msg
		return (1)
	end
end
else goto keys_ok

if @col6a is not NULL
begin
	select @cnt = @cnt + 1, @key6a = a.colid, @key6b = b.colid
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
			where a.name = @col6a
				and a.id = object_id(@tabaname)
				and b.name = @col6b
				and b.id = object_id(@tabbname)
				and y.type = "J"
				and a.type = y.low
				and z.type = "J"
				and b.type = z.low
				and y.number = z.number
	if @key6a IS  NULL
	begin
		/*
		** 17399, "The tables have no such sixth column or the columns are of different types."
		*/
		exec sp_getmessage 17399, @msg output
		print @msg
		return (1)
	end
end
else goto keys_ok

if @col7a is not NULL
begin
	select @cnt = @cnt + 1, @key7a = a.colid, @key7b = b.colid
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
			where a.name = @col7a
				and a.id = object_id(@tabaname)
				and b.name = @col7b
				and b.id = object_id(@tabbname)
				and y.type = "J"
				and a.type = y.low
				and z.type = "J"
				and b.type = z.low
				and y.number = z.number
	if @key7a is NULL
	begin
		/*
		** 17400, "The tables have no such seventh column or the columns are of different types."
		*/
		exec sp_getmessage 17400, @msg output
		print @msg
		return (1)
	end
end
else goto keys_ok

if @col8a is not NULL
begin
	select @cnt = @cnt + 1, @key8a = a.colid, @key8b = b.colid
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
			where a.name = @col8a
				and a.id = object_id(@tabaname)
				and b.name = @col8b
				and b.id = object_id(@tabbname)
				and y.type = "J"
				and a.type = y.low
				and z.type = "J"
				and b.type = z.low
				and y.number = z.number
	if @key8a is NULL
	begin
		/*
		** 17401, "The tables have no such eighth column or the columns are of different types."
		*/
		exec sp_getmessage 17401, @msg output
		print @msg
		return (1)
	end
end

/*
**  If we made it this far then all the columns for the common key are ok.
**  Everything is consistent so add the common key to syskeys.
*/
keys_ok:

insert syskeys (id, type, depid, keycnt, size, key1, key2, key3, key4, key5,
	key6, key7, key8, depkey1, depkey2, depkey3, depkey4, depkey5,
	depkey6, depkey7, depkey8)
values (object_id(@tabaname), 3, object_id(@tabbname), @cnt, 0, @key1a, 
	@key2a, @key3a, @key4a, @key5a,
	@key6a, @key7a, @key8a, @key1b, @key2b, @key3b, @key4b, @key5b,
	@key6b, @key7b, @key8b)   

/*
** 17402, "New common key added."
*/
exec sp_getmessage 17402, @msg output
print @msg
go
exec sp_procxmode 'sp_commonkey', 'anymode'
go
grant execute on sp_commonkey to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_cursorinfo')
begin
	drop procedure sp_cursorinfo
end
go
print "Installing sp_cursorinfo"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

create procedure sp_cursorinfo 
@cursor_level int = null,		/* nesting level for cursor */
@cursor_name  varchar(30) = null	/* cursor name */
as

	if @@trancount = 0
	begin
		set chained off
	end
	set transaction isolation level 1

	/* set cursor level to -1 to get cursor info for all nesting levels */
	if @cursor_level is null
		select @cursor_level = -1

	/* Do the work */
	dbcc cursorinfo(@cursor_level, @cursor_name)

return(0)

go
exec sp_procxmode 'sp_cursorinfo', 'anymode'
go
grant execute on sp_cursorinfo to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dboption')
begin
	drop procedure sp_dboption
end
go
print "Installing sp_dboption"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/a_values */

/*
** Messages for "sp_dboption"           17420
**      Use "langid" when looking at spt_values ???
**
** 17260, "Can't run %1! from within a transaction." 
** 17420, "Settable database options."
** 17421, "No such database -- run sp_helpdb to list databases."
** 17422, "The 'master' database's options can not be changed."
** 17423, "Usage: sp_dboption [dbname, optname, {true | false}]"
** 17424, "Database option doesn't exist or can't be set by user."
** 17425, "Run sp_dboption with no parameters to see options."
** 17426, "Database option is not unique."
** 17428, "You must be in the 'master' database in order to change
**	database options."                                
** 17429, "The database is currently in use -- 'read only' option
**	disallowed."                                       
** 17430, "Run the CHECKPOINT command in the database that was changed."
** 17431, "true"
** 17432, "false"
** 17433, "Database option '%1!' turned ON for database '%2!'."
** 17434, "Database option '%1!' turned OFF for database '%2!'."
** 17289, "Set your curwrite to the hurdle of current database."
** 17436, "The 'single user' option is not valid for the 'tempdb'
**	database."
*/

create procedure sp_dboption
@dbname varchar(30) = NULL,		/* database name to change */
@optname varchar(20) = NULL,		/* option name to turn on/off */
@optvalue varchar(10) = NULL		/* true or false */
as

declare @dbid int			/* dbid of the database */
declare @dbuid int			/* id of the owner of the database */
declare @statvalue smallint,		/* number of option */
	@stattype char(2),		/* status field flag */
	@statopt smallint,		/* option mask, part 1 */
	@stat2opt smallint		/* option mask, part 2 */
declare @optcount int			/* number of options like @optname */
declare @success_msg varchar(255)	/* success status message */
declare @msg varchar(250)
declare @sptlang	int
declare @true		varchar(10)
declare @false		varchar(10)
declare @whichone	int		/* which language? */
declare @name		varchar(30)
declare	@optmsgnum	int		/* identify one msgnum to compare */
declare	@msgcnt		int		/* count distinct dups */



if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @sptlang = @@langid,  @whichone = 0

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17050 and 17069
		and langid = @@langid)
	select @sptlang = 0
end


/*
**  If no @dbname given, just list the possible dboptions.
**  Only certain status bits may be set or cleared.  
**	   settable                	    not settable
**      ------------------------------  --------------------------
**	allow select into/bulkcopy (4)	don't recover (32)
**	read only (1024)		not recovered (256)
**	dbo use only (2048)		dbname has changed (16384)
**	single user (4096)
**	truncate log on checkpoint (8)
**	no checkpoint on recovery (16)
**	allow null (8192)
**	ddl in tran (512)
**      ALL SETTABLE OPTIONS (15900)
**	abort xact on log full (1, type='D2')
**	no space accounting (2, type='D2')
**	auto identity(4, type='D2')
**	identity in nonunique index(8, type='D2')
*/

/*
** Look for the "settable options" mask in spt_values
*/
select @statopt = number
from master.dbo.spt_values
where type = "D"
  and name = "ALL SETTABLE OPTIONS"

select @stat2opt = number
from master.dbo.spt_values
where type = "D2"
  and name = "ALL SETTABLE OPTIONS"

/*
** If we can't find the option masks, guess at them
*/
if @statopt is null
	select @statopt  = 4 | 8 | 16 | 512 | 1024 | 2048 | 4096 | 8192
if @stat2opt is null
	select @stat2opt = 1 | 2 | 4 | 8

if @dbname is null
begin
	/*
	** 17420, "Settable database options."
	*/
	exec sp_getmessage 17420, @msg output
	print @msg

	if @sptlang = 0
	    select database_options = name
		from master.dbo.spt_values
		where ((type = "D"
			and number & @statopt = number
			and number & @statopt != @statopt)
		    or (type = "D2"
			and number & @stat2opt = number
			and number & @stat2opt != @stat2opt))
		order by name
	else
	    select database_options = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
		where ((type = "D"
			and number & @statopt = number
			and number & @statopt != @statopt)
		    or (type = "D2"
			and number & @stat2opt = number
			and number & @stat2opt != @stat2opt))
		  and msgnum = error
		  and langid = @sptlang
		order by name
	return (0)
end

/*
**  Verify the database name and get the @dbid and @dbuid
*/
select @dbid = dbid, @dbuid = suid
	from master.dbo.sysdatabases
		where name = @dbname

/*
**  If @dbname not found, say so and list the databases.
*/
if @dbid is NULL
begin
	/*
	** 17421, "No such database -- run sp_helpdb to list databases."
	*/
	exec sp_getmessage 17421, @msg output
	print @msg
	return (1)
end

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((suser_id() != @dbuid) and (proc_role("sa_role") != 1))
	return(1)

/*
**  You can not change any of the options in master.  If the user tries to
**  do so tell them they can't.
*/
if @dbid = 1
begin
	/*
	** 17422, "The 'master' database's options can not be changed."
	*/
	exec sp_getmessage 17422, @msg output
	print @msg
	return (1)
end

/*
**  Check remaining parameters.
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
/* 17432, "false" */
exec sp_getmessage 17432, @false out
if @optname is NULL or lower(@optvalue) not in 
	("true", "false", @true, @false) or @optvalue is null
begin
	/*
	** 17423, "Usage: sp_dboption [dbname, optname, {true | false}]"
	*/
	exec sp_getmessage 17423, @msg output
	print @msg
	return (1)
end

/*
**  Use @optname and try to find the right option.
**  If there isn't just one, print appropriate diagnostics and return.
*/
select @optcount = count(*)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
/*
**  If more than one option like @optname, make sure they are not the same
**  option ("trunc" and "trunc.", for example)
*/
if @optcount > 1
begin
	select  @optmsgnum = msgnum
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))

	select @msgcnt = count(msgnum)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
	          and msgnum != @optmsgnum

	/* 
	** msgcnt of 0 indicates we really have just 1 unique dboption, 
	** probably due to alternate spelling.
	*/
	if (@msgcnt = 0) 
		select @optcount = 1
end
/*
** If no option, and alternate language is set, use other language
*/
if @optcount = 0 and @sptlang != 0
begin
    select @optcount = count(*)
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang
    select @whichone = 1
    /*
    **  If more than one option like @optname, make sure they are not the same
    **  option ("trunc" and "trunc.", for example)
    */
    if @optcount > 1
    begin
	select  @optmsgnum = msgnum
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang

	select @msgcnt = count(msgnum)
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
		  and msgnum = error
		  and langid = @sptlang
	          and msgnum != @optmsgnum

	/* 
	** msgcnt of 0 indicates we really have just 1 unique dboption, 
	** probably due to alternate spelling.
	*/
	if (@msgcnt = 0) 
		select @optcount = 1
    end
end

/*
**  If no option, show the user what the options are.
*/
if @optcount = 0
begin
	/*
	** 17424, "Database option doesn't exist or can't be set by user."
	*/
	exec sp_getmessage 17424, @msg output
	print @msg

	/*
	** 17425, "Run sp_dboption with no parameters to see options."
	*/
	exec sp_getmessage 17425, @msg output
	print @msg
	return (0)
end

/*
**  If more than one option like @optname, show the duplicates and return.
*/
if @optcount > 1
begin
	/*
	** 17426, "Database option is not unique."
	*/
	exec sp_getmessage 17426, @msg output
	print @msg

	if @sptlang = 0
	    select duplicate_options = name
		from master.dbo.spt_values
			where name like "%" + @optname + "%"
			  and ((type = "D"
				and number & @statopt = number)
			    or (type = "D2"
				and number & @stat2opt = number))
	else
	    select duplicate_options = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
			where (name like "%" + @optname + "%"
				or description like "%" + @optname + "%")
			  and ((type = "D"
				and number & @statopt = number)
			    or (type = "D2"
				and number & @stat2opt = number))
			  and msgnum = error
			  and langid = @sptlang

	return (1)
end


if db_name() != "master"
begin
	/*
	** 17428, "You must be in the 'master' database in order to change database options."                                
	*/
	exec sp_getmessage 17428, @msg output
	print @msg
	return (1)
end

/*
** User cannot set "tempdb" database in single user mode.
*/
select @statvalue = number
   from master.dbo.spt_values
	where name like "%" + @optname + "%"
	  and ((type = "D"
		and number & @statopt = number)
	    or (type = "D2"
		and number & @stat2opt = number))
 
if (@dbid = 2) and (@statvalue = 4096)
begin
	/*
	** 17436, "The 'single user' option is not valid for the 'tempdb'
	**         database."
	*/
	exec sp_getmessage 17436, @msg output
	print @msg, "sp_dboption"
	return (1)
end

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_dboption"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Get the number which is the bit value to set
*/
if @whichone = 0
    select @statvalue = number, @stattype = type, @success_msg = name
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%"
		  and ((type = "D"
			and number & @statopt = number)
		    or (type = "D2"
			and number & @stat2opt = number))
else
    select @statvalue = number, @stattype = type, @success_msg = name
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%"
			and ((type = "D"
			      and number & @statopt = number)
			  or (type = "D2"
			      and number & @stat2opt = number))
			and msgnum = error
			and langid = @sptlang


/*
**  Now update sysdatabases.

*/
if lower(@optvalue) in ("true", @true)
begin
	/*
	**  If this the option to make the database read only,
	**  we need to do some checking first.
	**  Unless it's the master db, no one can be using it.
	**  If it's the master db, only the SA may be using it.
	*/
	if (@statvalue = 1024) and (select count(*)
					from master.dbo.sysprocesses
						where dbid = @dbid) > 0
	begin
		/*
		** 17429, "The database is currently in use -- 'read only' option disallowed."                                       
		*/
		exec sp_getmessage 17429, @msg output
		print @msg
		return (1)
	end

	if (@stattype = "D")
		update master.dbo.sysdatabases
			set status = status | @statvalue
				where dbid = @dbid
	else
		update master.dbo.sysdatabases
			set status2 = status2 | @statvalue
				where dbid = @dbid
	/*
	** 17433, "Database option %1! turned ON for database %2!."
	*/
	exec sp_getmessage 17433, @msg output
	select @name = db_name(@dbid)
	print @msg, @success_msg, @name
end

/*
**  We want to turn it off.
*/
else
begin
	if (@stattype = "D")
		update master.dbo.sysdatabases
			set status = status & ~@statvalue
				where dbid = @dbid
	else
		update master.dbo.sysdatabases
			set status2 = status2 & ~@statvalue
				where dbid = @dbid
	/*
	** 17434, "Database option %1! turned OFF for database %2!."
	*/
	exec sp_getmessage 17434, @msg output
	select @name = db_name(@dbid)
	print @msg, @success_msg, @name
end

/*
**  Advise the user to run the CHECKPOINT command in the database that
**  was changed.
*/
/*
** 17430, "Run the CHECKPOINT command in the database that was changed."
*/
exec sp_getmessage 17430, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dboption', 'anymode'
go
grant execute on sp_dboption to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_defaultdb')
begin
	drop procedure sp_defaultdb
end
go
print "Installing sp_defaultdb"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.2	28.1	05/14/90	sproc/src/defaultdb */

/*
** Messages for "sp_defaultdb"          17440
** 
** 17260, "Can't run %1! from within a transaction."
** 17231, "No login with the specified name exists."
**      (was "No such login exists.")
** 17440, "Database name not valid -- default not changed."
** 17441, "You can't change someone else's default database."
** 17442, "Default database changed." 
** 17443, "Error in updating the default database."
*/

create procedure sp_defaultdb
@loginame varchar(30),			/* login name of the user */
@defdb varchar(30) 			/* default db for the user */
as

declare @msg varchar(250)

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_defaultdb"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Only the Account Owner or
**  Accounts with SA role can execute it.
**	RESOLVE_B1: Backport note: This check must be done
**		prior login and dbname checks.
*/
if ((suser_name() != @loginame) and (proc_role("sa_role") != 1))
	return(1)



/*
**  Check that the account exists.
*/
if not exists (select *
	from master.dbo.syslogins
	where name = @loginame)
begin
	/*
	** 17231, "No login with the specified name exists."
	*/
	exec sp_getmessage 17231, @msg output
        print @msg
	return (1)
end



/*
**  Check that the database name is valid.
*/
if not exists (select *
	from master.dbo.sysdatabases
	where name = @defdb)
begin
	/*
	** 17440, "Database name not valid -- default not changed."
	*/
	exec sp_getmessage 17440, @msg output
        print @msg
	return (1)
end

/*
**  Change the database
*/
update master.dbo.syslogins
	set dbname = @defdb
	where name = @loginame

if @@rowcount = 1
begin
	/*
	** 17442, "Default database changed." 
	*/
	exec sp_getmessage 17442, @msg output
	print @msg
	return (0)
end
else
begin
	/*
	** 17443, "Error in updating the default database."
	*/
	exec sp_getmessage 17443, @msg output
	print @msg
	return (1)
end
go
exec sp_procxmode 'sp_defaultdb', 'anymode'
go
grant execute on sp_defaultdb to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_databases')
begin
	drop procedure sp_databases
end
go
print "Installing sp_databases"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

create procedure sp_databases
as

	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	/* Use temporary table to sum up database size w/o using group by */
	create table #databases (
				  database_name varchar(32),
				  size int)

	/* Insert row for each database */
	insert into #databases
		select
			name,
			(select sum(size) from master.dbo.sysusages
				where dbid = d.dbid)
		from master.dbo.sysdatabases d

	select
		 database_name,
				/* Convert from number of pages to K */
		 database_size = size * (@@pagesize / 1024),
		 remarks = convert(varchar(254),null)	/* Remarks are NULL */
	from #databases

	return(0)
go
go
exec sp_procxmode 'sp_databases', 'anymode'
go
grant execute on sp_databases to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dbremap')
begin
	drop procedure sp_dbremap
end
go
print "Installing sp_dbremap"
go

/* Sccsid = "@(#) generic/sproc/src/%M% %I% %G%" */

/*
** Messages for "sp_dbremap"      17550
**
** 17260, "Can't run %1! from within a transaction."
** 17284, "'%1!' is not a valid identifier."
** 17590, "The specified database does not exist."
*/

create procedure sp_dbremap
@dbname varchar(30)	/* name of database whose diskmap is to be remapped */
as

declare	@msg	varchar(250)
declare @procval int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
** Check for valid identifier.
*/
if valid_name(@dbname) = 0
begin
	/*
	** 17284, "'%1!' is not a valid identifier."
	*/
	exec sp_getmessage 17284, @msg output
	print @msg, @dbname
	return (1)
end


/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  if user  had SA role he would be the dbo hence check only
**  whether user is DBO.
**  Call proc_role() with the required SA role.
*/
if (user_id() = 1)
begin    
        /* If user has sa role audit this as a successful sa
        ** command execution.
        */
        if charindex("sa_role",show_role()) > 0
                select @procval = proc_role("sa_role")
end
else 
begin
        /* user_id() is not DBO hence user does not have SA role
        ** audit this as a failed sa command execution.
        */
        select @procval = proc_role("sa_role")
        return (1)
end

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
 	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "dbremap"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see if the database exists.
*/
if not exists (select *
		from master.dbo.sysdatabases
			where name = @dbname)
begin
	/*
	** 17590, "The specified database does not exist."
	*/
	exec sp_getmessage 17590, @msg output
        print @msg
	return (1)
end


/*
**  Now go ahead and update the in-core image of the database usage map table.
*/
dbcc dbrepair (@dbname, remap)


return (0)
go
exec sp_procxmode 'sp_dbremap', 'anymode'
go
grant execute on sp_dbremap to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_remap')
begin
	drop procedure sp_remap
end
go
print "Installing sp_remap"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** 17732, "You do not own table '%1!'."
** 17461, "Object does not exist in this database."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/
CREATE PROCEDURE sp_remap
@objname 	varchar(92)		/* object to remap */
AS

/*
**	Local variables here
*/
DECLARE @procid	int,			/* object id of the procedure */
	@dbname varchar(30),
	@uname	varchar(32),
	@msg	varchar(255)


IF @@trancount = 0
BEGIN
	SET chained off
END

SET transaction isolation level 1

/*
**  It is not proper to qualify the object names,
**  specify the database name as second parameter.
*/
IF @objname LIKE "%.%.%"
BEGIN
	/* The object is of the form database.owner.table; extract owner */
	SELECT @uname = substring(@objname, charindex(".", @objname) + 1, 255)
	SELECT @objname = substring(@uname, charindex(".", @uname) + 1, 255)
	SELECT @uname = substring(@uname, 1, charindex(".", @uname) - 1)

	/* If the object belong to the current user or to the dbo */
	IF (user_name() != @uname AND user_id() != 1)
	BEGIN
		/* 17732, "You do not own table '%1!'." */
		exec sp_getmessage 17732, @msg output
		print @msg, @objname
	END		
END

/*
**	Get the object id.  Verify this is executed by object owner or dbo.
*/
SELECT @procid  = id
FROM   sysobjects
WHERE  name = @objname
       AND (uid = user_id() OR user_id() = 1)
       AND type IN ('V ', 'P ', 'R ', 'D ', 'TR')

/*
**  If the object doesn't exist, return.
*/
IF @procid = NULL
BEGIN
	/* 17461, "Object does not exist in this database." */
	exec sp_getmessage 17461, @msg out
	print @msg
	return (1)
END

/*
**	Obtain current database information
*/
SELECT @dbname = db_name()

/*
**  Do the actual remap here now that we have the object id.
**  The command is run in the current database.
*/

DBCC REMAP(@procid, @dbname, 1)

go
go
exec sp_procxmode 'sp_remap', 'anymode'
go
grant execute on sp_remap to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_depends')
begin
	drop procedure sp_depends
end
go
print "Installing sp_depends"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_depends"            17460
**
** 17460, "Object must be in the current database."
** 17461, "Object does not exist in this database."
** 17462, "Things the object references in the current database."
** 17463, "Things inside the current database that reference the object."
** 17464, "Object doesn't reference any object and no objects reference it."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_depends
@objname varchar(92)		/* the object we want to check */
as

declare @found_some bit			/* flag for dependencies found */
declare @msg varchar(250)
declare @sptlang	int		/* current sessions language */
declare @length		int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Make sure the @objname is local to the current database.
*/
if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
begin
	/*
	** 17460, "Object must be in the current database."
	*/
	exec sp_getmessage 17460, @msg output
	print @msg
	return (1)
end

/*
**  See if @objname exists.
*/
if not exists (select id
		from sysobjects
			where id = object_id(@objname))
begin
	/*
	** 17461, "Object does not exist in this database."
	*/
	exec sp_getmessage 17461, @msg output
	print @msg
	return (1)
end

/*
**  Initialize @found_some to indicate that we haven't seen any dependencies.
*/
select @found_some = 0

set nocount on

/*
**  Print out the particulars about the local dependencies.
*/
if exists (select *
		from sysdepends
			where id = object_id(@objname))
begin
	/*
	** 17462, "Things the object references in the current database."
	*/
	exec sp_getmessage 17462, @msg output
	print @msg

	select @sptlang = @@langid

	if @@langid != 0
	begin
		if not exists (
			select * from master.dbo.sysmessages where error
			between 17010 and 17014
			and langid = @@langid)
		    select @sptlang = 0
		else
		if not exists (
			select * from master.dbo.sysmessages where error
			between 17100 and 17109
			and langid = @@langid)
		    select @sptlang = 0
	end

	select @length = max(datalength(s.name + "." + o.name))
		    from sysobjects o,
			sysdepends d, sysusers s
		    where o.id = d.depid
			and d.id = object_id(@objname)
			and o.uid = s.uid

	if (@length > 40)
	    select object = s.name + "." + o.name,
		type = convert(char(16), m0.description),
		updated = convert(char(10), m1.description),
		selected = convert(char(10), m2.description)
			from sysobjects o, master.dbo.spt_values v,
				sysdepends d, master.dbo.spt_values u,
				master.dbo.spt_values w,
				sysusers s, 
				master.dbo.sysmessages m0, 
				master.dbo.sysmessages m1, 
				master.dbo.sysmessages m2
			where o.id = d.depid
				and o.sysstat & 15 = v.number and v.type = 'O'
				and v.msgnum = m0.error
				and isnull(m0.langid, 0) = @sptlang
				and u.type = 'B' and u.number = d.resultobj
				and u.msgnum = m1.error
				and isnull(m1.langid, 0) = @sptlang
				and w.type = 'B' and w.number = d.readobj
				and w.msgnum = m2.error
				and isnull(m2.langid, 0) = @sptlang
				and d.id = object_id(@objname)
				and o.uid = s.uid

	else
	    select object = convert(char(40), (s.name + "." + o.name)),
		type = convert(char(16), m0.description),
		updated = convert(char(10), m1.description),
		selected = convert(char(10), m2.description)
			from sysobjects o, master.dbo.spt_values v,
				sysdepends d, master.dbo.spt_values u,
				master.dbo.spt_values w,
				sysusers s, 
				master.dbo.sysmessages m0, 
				master.dbo.sysmessages m1, 
				master.dbo.sysmessages m2
			where o.id = d.depid
				and o.sysstat & 15 = v.number and v.type = 'O'
				and v.msgnum = m0.error
				and isnull(m0.langid, 0) = @sptlang
				and u.type = 'B' and u.number = d.resultobj
				and u.msgnum = m1.error
				and isnull(m1.langid, 0) = @sptlang
				and w.type = 'B' and w.number = d.readobj
				and w.msgnum = m2.error
				and isnull(m2.langid, 0) = @sptlang
				and d.id = object_id(@objname)
				and o.uid = s.uid


	select @found_some = 1
end

/*
**  Now check for things that the objects depends upon
*/
if exists (select *
		from sysdepends
			where depid = object_id(@objname))
begin
	/*
	** 17463, "Things inside the current database that reference the object."
	*/
	exec sp_getmessage 17463, @msg output
	print @msg
	select distinct
	       @length = max(datalength(s.name + "." + o.name))
			from sysobjects o,
				sysdepends d, sysusers s
			where o.id = d.id
				and d.depid = object_id(@objname)
				and o.uid = s.uid
	if (@length > 40)
	    select distinct
		object = s.name + "." + o.name,
		type = convert(char(16), v.name)
			from sysobjects o, master.dbo.spt_values v,
				sysdepends d, sysusers s
			where o.id = d.id
				and o.sysstat & 15 = v.number and v.type = 'O'
				and d.depid = object_id(@objname)
				and o.uid = s.uid
	else
	    select distinct
		object = convert(char(40), (s.name + "." + o.name)),
		type = convert(char(16), v.name)
			from sysobjects o, master.dbo.spt_values v,
				sysdepends d, sysusers s
			where o.id = d.id
				and o.sysstat & 15 = v.number and v.type = 'O'
				and d.depid = object_id(@objname)
				and o.uid = s.uid
	select @found_some = 1
end

/*
**  Did we find anything in sysdepends?
*/
if @found_some = 0
begin
	/*
	** 17464, "Object doesn't reference any object and no objects reference it."
	*/
	exec sp_getmessage 17464, @msg output
	print @msg
end

set nocount off

return (0)
go
exec sp_procxmode 'sp_depends', 'anymode'
go
grant execute on sp_depends to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_diskdefault')
begin
	drop procedure sp_diskdefault
end
go
print "Installing sp_diskdefault"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/diskdefault */

/*
** Messages for "sp_diskdefault"        17470
**
** 17260, "Can't run %1! from within a transaction." 
** 17470, "No such device exists -- run sp_helpdevice to list the DataServer devices."
** 17471, "The device name supplied is not a database disk."
** 17472, "Usage: sp_diskdefault logicalname {defaulton | defaultoff}." 
*/

create procedure sp_diskdefault
@logicalname	varchar(30),		/* logical name of the device */
@defstatus	varchar(15)		/* turn on or off */
as

declare @msg varchar(250)

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_diskfault"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  Make sure that a device with @logicalname exists.
*/
if not exists (select *
		from master.dbo.sysdevices
			where name = @logicalname)
begin
	/*
	** 17470, "No such device exists -- run sp_helpdevice to list the DataServer devices."
	*/
	exec sp_getmessage 17470, @msg output
	print @msg
	return (1)
end

/*
**  Make sure that is a database disk and not a dump device.
*/
if exists (select *
		from master.dbo.sysdevices
			where name = @logicalname 
				and status & 16 = 16)
begin
	/*
	** 17471, "The device name supplied is not a database disk."
	*/
	exec sp_getmessage 17471, @msg output
	print @msg
	return (1)
end

if @defstatus = "defaulton"
begin
	update master.dbo.sysdevices
		set status = status | 1
			where name = @logicalname
	return (0)
end

if @defstatus = "defaultoff"
begin
	update master.dbo.sysdevices
		set status = status & ~1
			where name = @logicalname
	return (0)
end

/*
**  @defstatus must be "defaulton" or "defaultoff"
*/
/*
** 17472, "Usage: sp_diskdefault logicalname {defaulton | defaultoff}." 
*/
exec sp_getmessage 17472, @msg output
print @msg

return (1)
go
exec sp_procxmode 'sp_diskdefault', 'anymode'
go
grant execute on sp_diskdefault to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropalias')
begin
	drop procedure sp_dropalias
end
go
print "Installing sp_dropalias"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_dropalias"          17480
**
** 17231, "No login with the specified name exists."
** 17480, "Alias user dropped."
** 17481, "No alias for specified user exists."
*/

create procedure sp_dropalias
@loginame varchar(30)		/* account name of the user with the alias */
as

declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
	return(1)

/*
**  Check to make sure that the @loginame has an account.
*/
if (select suser_id(@loginame)) is NULL
begin
	/*
	** 17231, "No login with the specified name exists."
	*/
	exec sp_getmessage 17231, @msg output
        print @msg
	return (1)
end

/*
**  Delete the alias, if any, from sysalternates.
*/
delete from sysalternates
	where suid = suser_id(@loginame)

/*
**  If nothing happened (rowcount = 0), there was no alias.
*/
if @@rowcount > 0
begin
	/*
	** 17480, "Alias user dropped."
	*/
	exec sp_getmessage 17480, @msg output
        print @msg
	return (0)
end
else
begin
	/*
	** 17481, "No alias for specified user exists."
	*/
	exec sp_getmessage 17481, @msg output
        print @msg
	return (1)
end
go
exec sp_procxmode 'sp_dropalias', 'anymode'
go
grant execute on sp_dropalias to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropdevice')
begin
	drop procedure sp_dropdevice
end
go
print "Installing sp_dropdevice"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/dropdevice */

/*
** Messages for "sp_dropdevice"         17482
**
** 17260, "Can't run %1! from within a transaction." 
** 17471, "No such device exists -- run sp_helpdevice to list the DataServer devices." 
** 17482, "Device is being used by a database. You can't drop it."
** 17483, "Device dropped."
*/

create procedure sp_dropdevice
@logicalname	varchar(30)		/* logical name of the device */
as
declare @msg varchar(250)
declare @len1 int, @len2 int

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_dropdevice"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  Check and make sure that the device actually exists.
*/
if not exists (select * 
		from master.dbo.sysdevices
			where name = @logicalname)
begin
	/*
	** 17471, "No such device exists -- run sp_helpdevice to list the DataServer devices." 
	*/
	exec sp_getmessage 17471, @msg output
        print @msg
	return (1)
end

/*
**  Check and make sure that no database is using the device.
**  If so, print out who is using it and exit.
*/
if exists (select *
	from master.dbo.sysdatabases a, master.dbo.sysusages b, 
			master.dbo.sysdevices c
		where a.dbid = b.dbid
			and c.low <= size + vstart
			and c.high >= size + vstart - 1
			and c.status & 2 = 2 
			and c.name = @logicalname)
begin
	/*
	** 17482, "Device is being used by a database. You can't drop it."
	*/
	exec sp_getmessage 17482, @msg output
        print @msg

	select @len1 = max(datalength(a.name)),
	       @len2 = max(datalength(c.name))
	from master.dbo.sysdatabases a, master.dbo.sysusages b, 
			master.dbo.sysdevices c
		where a.dbid = b.dbid
			and c.low <= size + vstart
			and c.high >= size + vstart - 1
			and c.status & 2 = 2 
			and c.name = @logicalname

	if (@len1 > 23 or @len2 > 21)
	    select database_name = a.name,
		device = c.name,
		size = convert(varchar(25), size / 500) + " MB"
	    from master.dbo.sysdatabases a, master.dbo.sysusages b, 
			master.dbo.sysdevices c
		where a.dbid = b.dbid
			and c.low <= size + vstart
			and c.high >= size + vstart - 1
			and c.status & 2 = 2 
			and c.name = @logicalname
	    order by a.name, c.name, size
	else
	    select database_name = convert(char(23), a.name),
		device = convert(char(21), c.name),
		size = convert(varchar(25), size / 500) + " MB"
	    from master.dbo.sysdatabases a, master.dbo.sysusages b, 
			master.dbo.sysdevices c
		where a.dbid = b.dbid
			and c.low <= size + vstart
			and c.high >= size + vstart - 1
			and c.status & 2 = 2 
			and c.name = @logicalname
	    order by a.name, c.name, size

	return (1)
end


/*
**  Everything's ok so drop the device.
*/
delete master.dbo.sysdevices
	where name = @logicalname

/*
** 17483, "Device dropped."
*/
exec sp_getmessage 17483, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dropdevice', 'anymode'
go
grant execute on sp_dropdevice to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropgroup')
begin
	drop procedure sp_dropgroup
end
go
print "Installing sp_dropgroup"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/dropgroup */

/*
** Messages for "sp_dropgroup"          17486
**
** 17333, "No group with the specified name exists." 
** 17486, "Can't drop the group 'public'."
** 17487, "You cannot drop group because it owns objects in database."
** 17488, "Group has members.  It must be empty before it can be dropped."
** 17489, "Group has been dropped."
** 18075, "Set your maxwrite label correctly."
*/

create procedure sp_dropgroup
@grpname varchar(30)		/* group to be dropped */
as

declare @gid smallint		/* group id of the group to be dropped */
declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end



set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
	return(1)

/*
**  See if the group exists.
**  User ids range from -16383 to +16383 and group ids are > 16383.
*/
select @gid = uid
	from sysusers
		where name = @grpname
			and (uid > 16383 or uid = 0)
	and not exists (select name from master.dbo.syssrvroles        
                        where name = @grpname)

if @gid is NULL
begin
	/*
	** 17333, "No group with the specified name exists." 
	*/
	exec sp_getmessage 17333, @msg output
	print @msg
	return (1)
end

/*
**  Can't drop the group public.
*/
if @gid = 0
begin
	/*
	** 17486, "Can't drop the group 'public'."
	*/
	exec sp_getmessage 17486, @msg output
	print @msg
	return (1)
end

/*
**  Check to see if the group owns anything.  If so, return.
*/
if exists (select *
		   from sysobjects
			   where uid = @gid)
begin
	/*
	** 17487, "You cannot drop group because it owns objects in database."
	*/
	exec sp_getmessage 17487, @msg output
	print @msg

	/*
	**  Show what is owned by the group.
	*/
	select s.name, s.type, owner = u.name
		from sysobjects s, sysusers u
			where s.id = @gid
				and u.uid = @gid
	return (1)
end


/*
**  Check to see that nobody is in the group.  If so, return.
*/
if (select count(*)
	from sysusers
		where gid = @gid
			and uid <= 16383) != 0
begin
	/*
	** 17488, "Group has members.  It must be empty before it can be dropped."
	*/
	exec sp_getmessage 17488, @msg output
	print @msg

	/*
	**  Show who is in the group.
	*/
	select name
		from sysusers
			where gid = @gid
				and uid <= 16383
	
	return (1)
end

/*
**  Drop the group.
**  Also drop any references to the group in the sysprotects table.
*/
begin transaction


	delete from sysusers
		where uid = @gid



	delete from sysprotects
		where uid = @gid


commit transaction

/*
** 17489, "Group has been dropped."
*/
exec sp_getmessage 17489, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dropgroup', 'anymode'
go
grant execute on sp_dropgroup to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropkey')
begin
	drop procedure sp_dropkey
end
go
print "Installing sp_dropkey"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_dropkey"            17490
**
** 17390, "Table or view name must be in 'current' database." 
** 17490, "Usage: sp_dropkey {primary | foreign | common}, tabname [,deptabname]."
** 17491, "Type must be 'primary', 'foreign', or 'common'."
** 17492, "The table or view named doesn't exist in the current database."
** 17493, "You must be the owner of the table or view to drop its key."
** 17494, "No primary key for the table or view exists."
** 17495, "Primary key for the table or view dropped."
** 17496, "Dependent foreign keys were also dropped."
** 17497, "You need to supply the dependent table or view as the third parameter."      
** 17498, "The dependent table or view doesn't exist in the current database."          
** 17499, "No foreign key for the table or view exists."
** 17500, "Foreign key dropped."
** 17501, "No common keys exist between the two tables or views supplied."
** 17502, "Common keys dropped."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_dropkey
@keytype varchar(10), 			/* type of key to drop */
@tabname varchar(92),			/* table with the key */
@deptabname varchar(92) = null		/* dependent table */
as

declare @uid smallint			/* owner of @tabname */
declare @depuid smallint		/* owner of @related table */
declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  First make sure that the key type is ok.
*/
if @keytype not in ("primary", "foreign", "common")
begin
	/*
	** 17490, "Usage: sp_dropkey {primary | foreign | common}, tabname [,deptabname]."
	*/
	exec sp_getmessage 17490, @msg output
	print @msg
	/*
	** 17491, "Type must be 'primary', 'foreign', or 'common'."
	*/
	exec sp_getmessage 17491, @msg output
	print @msg
	return (1)
end

/*
**  Check to see that the tabname is local.
*/
if @tabname like "%.%.%"
begin
	if substring(@tabname, 1, charindex(".", @tabname) - 1) != db_name()
	begin
		/*
		** 17390, "Table or view name must be in 'current' database." 
		*/
		exec sp_getmessage 17390, @msg output
		print @msg
		return (1)
	end
end
if @deptabname like "%.%.%"
begin
	if substring(@deptabname, 1, charindex(".", @deptabname) - 1) != db_name()
	begin
		/*
		** 17390, "Table or view name must be in 'current' database."
		*/
		exec sp_getmessage 17390, @msg output
		print @msg
		return (1)
	end
end

/*
**  Get the ids of the @tabname and @deptabname.
*/
if not exists (select *
		from sysobjects
			where id = object_id(@tabname))
begin
	/*
	** 17492, "The table or view named doesn't exist in the current database."
	*/
	exec sp_getmessage 17492, @msg output
	print @msg
	return (1)
end

/*
** Get the user-id of @tabname
*/
select @uid = uid
	from sysobjects
		where id = object_id(@tabname)

if @uid != user_id()
begin
	/*
	** 17493, "You must be the owner of the table or view to drop its key."
	*/
	exec sp_getmessage 17493, @msg output
	print @msg
	return (1)
end

/*
**  If primary key, just drop it.
*/
if @keytype = "primary"
begin
	delete from syskeys
		where id = object_id(@tabname)
			and type = 1

	if @@rowcount = 0
	begin
		/*
		** 17494, "No primary key for the table or view exists."
		*/
		exec sp_getmessage 17494, @msg output
		print @msg
		return (1)
	end

	else
	begin
		/*
		** 17495, "Primary key for the table or view dropped."
		*/
		exec sp_getmessage 17495, @msg output
		print @msg
	end

	/*
	**  Check to see if there are any foreign keys dependent on the
	**  primary key.  If so -- drop them.
	*/
	delete from syskeys
		where depid = object_id(@tabname)
			and type = 2
	
	if @@rowcount != 0
	begin
		/*
		** 17496, "Dependent foreign keys were also dropped."
		*/ 
		exec sp_getmessage 17496, @msg output
		print @msg
	end

	return (0)
end

/*
**  It's either a foreign or common key so we need to verify the
**  existence of the @deptabname.
*/
if not exists (select id
			from sysobjects
				where id = object_id(@deptabname))
begin
	/*
	**  Was the @deptabname supplied?
	*/
	if @deptabname is null
	begin
		/*
		** 17497, "You need to supply the dependent table or view as the third parameter."      
		*/
		exec sp_getmessage 17497, @msg output
		print @msg
		return (1)
	end

	/*
	**  It was supplied but it doesn't exist.
	*/
	/*
	** 17498, "The dependent table or view doesn't exist in the current database."          
	*/
	exec sp_getmessage 17498, @msg output
	print @msg
	return (1)
end


/*
**  If foreign key, get rid of it.
*/
if @keytype = "foreign"
begin
	/*
	**  Get rid of the foreign key entry.
	*/
	delete from syskeys
		where type = 2
			and id = object_id(@tabname)
			and depid = object_id(@deptabname)
	if @@rowcount = 0
	begin
		/*
		** 17499, "No foreign key for the table or view exists."
		*/
		exec sp_getmessage 17499, @msg output
		print @msg
		return (1)
	end

	/*
	** 17500, "Foreign key dropped."
	*/
	exec sp_getmessage 17500, @msg output
	print @msg

	return (0)
end

/*
**  Key type must be common so just get rid of the common keys
**  with the right ids and depids.  Since whenever a common key is defined
**  it is added to both of the tables involved, we'll get rid of both of
**  those entries.
*/
delete from syskeys
	where type = 3
		and id = object_id(@tabname)
		and depid = object_id(@deptabname)

if @@rowcount = 0
begin
	/*
	** 17501, "No common keys exist between the two tables or views supplied."
	*/
	exec sp_getmessage 17501, @msg output
	print @msg
	return (1)
end

/*
**  Now get rid of the inverse common key entries.
*/
delete from syskeys
	where type = 3
		and id = object_id(@deptabname)
		and depid = object_id(@tabname)

/*
** 17502, "Common keys dropped."
*/
exec sp_getmessage 17502, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dropkey', 'anymode'
go
grant execute on sp_dropkey to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_droplogin')
begin
	drop procedure sp_droplogin
end
go
print "Installing sp_droplogin"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/droplogin */

/*
** Messages for "sp_droplogin"          17509
**
** 17260, "Can't run %1! from within a transaction." 
** 17231, "No login with the specified name exists."
** 17509, "User exists or is an alias in atleast one database.  Drop user/alias before dropping login."
** 17880, "No such account -- nothing changed."
** 17915, "Warning:  the specified account is currently active."
** 17916, "Cannot lock the last remaining unlocked SSO account."

** 17511, "Login dropped."
*/

create procedure sp_droplogin
@loginame varchar(30)		/* name of login account to drop */
as

declare @msg varchar (250)
declare @suid int		/* suid of person to change pw on    */
declare @returncode int

/*
**  This procedure makes a weak attempt to check for any dependencies.
**  It looks in the current database to see if the suid is used in
**  sysusers or sysalternates.  If so, a diagnostic is issued and the
**  login is not dropped.
**
**  Ideally, this procedure should check each database to see if the login
**  is a user.  However, this is not yet possible since procedures do not
**  allow parameters to be used for database or table names.
*/

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_droplogin"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  Check sysusers.
*/
if valid_user(suser_id(@loginame)) = 1
begin
	/*
	** 17509, "User exists or is an alias in atleast one database.  Drop user/alias before dropping login."
	*/
	exec sp_getmessage 17509, @msg output
	print @msg
	return (1)
end

/*
**  Check if the account exists
*/
select @suid = suid 
	from master.dbo.syslogins
	where name = @loginame
if @suid is NULL
begin
        /*
        ** 17880, "No such account -- nothing changed."
        */
        exec sp_getmessage 17880, @msg output
        print @msg
        return (1)
end

/*
**  Disallow dropping an account who has already logged in.
**  Note that it eliminates the race condition between two processes
**  for checking the last remaining unlocked SSO account.
*/
if exists (select * from master.dbo.sysprocesses where suid = @suid)
begin
	/* 17915,
	** "Warning: the specified account is currently active."
	*/
	exec sp_getmessage 17915, @msg output
	print @msg
	/*
	** 17918, "Nothing changed."
	*/
	exec sp_getmessage 17918, @msg output
	print @msg
	return (1)
end


/*
**  Lock the account to prevent it from begin active.
*/
execute @returncode = sp_locklogin @loginame, "lock"
if (@returncode != 0)
	return (@returncode)

/*
**  Delete the login.
*/
delete from master.dbo.syslogins
	where name = @loginame

/*
**  Check @@rowcount when it works
*/
if @@rowcount > 0
begin
	/* remove all roles related information from sysloginroles */
	delete from master.dbo.sysloginroles
		where suid = @suid

	/*  delete entries from sysattributes for this login */
	delete from master.dbo.sysattributes
		where object_type = "L"
		and object = @suid

	/* delete entries in sysremotelogins for this login */
	delete from master.dbo.sysremotelogins
		where suid = @suid

	/*
	** 17511, "Login dropped."
	*/
	exec sp_getmessage 17511, @msg output
	print @msg
	return (0)
end
else
begin
	/*
	** 17231, "No login with the specified name exists."
	*/
	exec sp_getmessage 17231, @msg output
	print @msg
	return (1)
end
go
exec sp_procxmode 'sp_droplogin', 'anymode'
go
grant execute on sp_droplogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropthreshold')
begin
	drop procedure sp_dropthreshold
end
go
print "Installing sp_dropthreshold"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_dropthreshold"      17903
**
** 17871, "There is no segment named '%1!'."
** 17875, "Only the DBO of database '%1!' or a user with System Administrator
**	   (SA) authorization may add, delete, or modify thresholds in that
**	   database."
** 17903, "Table '%1!' does not exist in database '%2!' -- cannot drop
**	  thresholds."
** 17904, "Segment '%1!' does not have a threshold at '%2!' pages."
** 17905, "You may not drop the log's last-chance threshold."
** 17906, "Dropping threshold for segment '%1!' at '%2!' pages."
** 17289, "Set your curwrite to the hurdle of current database."
*/

create procedure sp_dropthreshold
@dbname		varchar(30),		/* current database name */
@segname	varchar(30),		/* segment name		*/
@free_space	int			/* threshold level	*/
as

declare	@segno	int,
	@status	smallint,
	@msg	varchar(255)

/*
** If we are under a user defined xact, disallow this since we may
** leave the dbtable's threshold cache out-of-sync if the end user
** rollbacks its xact.
*/
if @@trancount > 0
begin
     /*
		 ** 17260, "Can't run %1! from within a transaction."
		 */
		 exec sp_getmessage 17260, @msg output
		 print @msg, "sp_dropthreshold"
		 return (1)
end

set transaction isolation level 1
set chained off

/*
** Make sure we are in the right database
*/
if (@dbname != db_name())
begin
	/*
	** 18031, "You are in the wrong database.  Say 'USE %1!', then run
	**         this procedure again."
	*/
	exec sp_getmessage 18031, @msg output
	print @msg, @dbname
	return (5)
end

/*
** Make sure our database is recent enough to contain Systhresholds
*/
if (select name from sysobjects
	where	name = 'systhresholds'
	  and	type = 'S')
   is NULL
begin
	/*
	** 17903, "Table '%1!' does not exist in database '%2!' -- cannot drop
	**	  thresholds."
	*/
	exec sp_getmessage 17903, @msg output
	print @msg, "systhresholds", @dbname
	return (1)
end

/*
** Make sure the user (is the DBO) or (has "sa_role")
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
begin
	/*
	** 17875, "Only the DBO of database %1! or a user with System
	** Administrator (SA) authorization may add, delete, or modify
	** thresholds in that database."
	*/
	exec sp_getmessage 17875, @msg output
	print @msg, @dbname
	return (1)
end



/*
** Make sure the segment name is valid.
*/
select @segno = segment from syssegments where name = @segname
if @segno is NULL
begin
	/*
	** 17871, "There is no segment named '%1!'."
	*/
	exec sp_getmessage 17871, @msg output
	print @msg, @segname
	return (2)
end

/*
** Make sure the threshold exists
*/
if (select free_space from systhresholds
	where	segment = @segno
	  and	free_space = @free_space)
   is null
begin
	/*
	** 17904, "Segment '%1!' does not have a threshold at '%2!' pages."
	*/
	exec sp_getmessage 17904, @msg output
	print @msg, @segname, @free_space
	select segment_name=@segname, free_space
	from systhresholds
	where	segment = @segno

	return (3)
end

/* Make sure this is not the last-chance threshold for syslogs */
if @segname = 'logsegment' and
   (select status from systhresholds
	where segment = @segno
	  and free_space = @free_space) & 1 = 1
begin
	/*
	** 17905, "You may not drop the log's last-chance threshold."
	*/
	exec sp_getmessage 17905, @msg output
	print @msg
	return (4)
end

/*
** We have done all the tests we can.  Drop the threshold.
*/

/*
** 17906, "Dropping threshold for segment '%1!' at '%2!' pages."
*/
exec sp_getmessage 17906, @msg output
print @msg, @segname, @free_space

begin transaction delete_threshold
delete systhresholds
where	segment = @segno
  and	free_space = @free_space

if @@error != 0
begin
	rollback transaction
	/*
	** 17907, "Delete of systhresholds row failed."
	*/
	exec sp_getmessage 17907, @msg output
	print @msg
	return (1)
end
/*
** Last, rebuild the database threshold table
*/
dbcc dbrepair(@dbname, "newthreshold")


if @@error != 0
begin
rollback transaction
/*
** 17878, "Rebuild of the database threshold table failed."
 */
exec sp_getmessage 17878, @msg output
print @msg
return (1)
end

commit transaction

return (0)
go
exec sp_procxmode 'sp_dropthreshold', 'anymode'
go
grant execute on sp_dropthreshold to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_droptype')
begin
	drop procedure sp_droptype
end
go
print "Installing sp_droptype"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_droptype"           17540
**
** 17540, "The type doesn't exist or you don't own it."
** 17541, "Type is being used. You cannot drop it."
** 17542, "Type has been dropped."
** 18076, "Could not set curwrite to object level. Set your maxwrite label correctly."
*/

create procedure sp_droptype
@typename varchar(30)			/* the user type to drop */
as

declare @typeid smallint		/* the typeid of the usertype to drop */
declare @msg    varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Initialize @typeid so we can tell if we can't find it.
*/
select @typeid = 0

/*
**  Find the user type with @typename.  It must be a user type (usertype > 99)
**  and it must be owned by the person (or dbo) running the procedure.
*/
select @typeid = usertype
	from systypes
		where (uid = user_id() or user_id() = 1)
			and name = @typename
			and usertype > 99

if @typeid = 0
begin
	/*
	** 17540, "The type doesn't exist or you don't own it."
	*/
	exec sp_getmessage 17540, @msg output
	print @msg
	return (1)
end

/*
**  Check to see if the type is being used.  If it is, it can't be dropped.
*/
if exists (select *
		   from syscolumns
			   where usertype = @typeid)
begin
	/*
	** 17541, "Type is being used. You cannot drop it."
	*/
	exec sp_getmessage 17541, @msg output
	print @msg


	/*
	**  Show where it's being used.
	*/
	select object = o.name, type = o.type, owner = u.name, column = c.name,
		datatype = t.name
	from syscolumns c, systypes t, sysusers u, sysobjects o
		where c.usertype = @typeid
			and t.usertype = @typeid
			and o.uid = u.uid
			and c.id = o.id
	order by object, column

	return (1)
end

/*
**  Everything is consistent so drop the type.
*/
delete from systypes
	where usertype = @typeid

/*
** 17542, "Type has been dropped."
*/
exec sp_getmessage 17542, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_droptype', 'anymode'
go
grant execute on sp_droptype to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropuser')
begin
	drop procedure sp_dropuser
end
go
print "Installing sp_dropuser"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_dropuser"           17543
**
** 17232, "No user with the specified name exists in the current database."
** 17431, "true"
** 17432, "false"
** 17543, "You cannot drop the 'database owner'."
** 17544, "You cannot drop the 'guest' user from master or tempdb."
** 17545, "You cannot drop user because user '%1!' owns objects in database."
** 17546, "You cannot drop user because user '%1!' owns types in database."
** 17547, "The dependent aliases were also dropped."
** 17548, "User has been dropped from current database."
** 17549, "You cannot drop user because user '%1!'  owns grantable
**         privileges and granted them to other users.  The user
** 	   has granted the following privileges:"
** 17673, "All"
** 18033, "You cannot drop user because user '%1!' owns thresholds in database."
** 18053, "User '%1!' was granted grantable privileges by the following users:"
** 18075, "Set your maxwrite label correctly."
*/

create procedure sp_dropuser
@name_in_db varchar(30)			/* user name to drop */
as

declare @suid int			/* suid of the user */
declare @uid smallint			/* uid of the user */
declare @objectcount int		/* count of objects user owns */
declare @typecount int			/* count of types user owns */
declare @grantcount int			/* count of grants user made */
declare	@userdropped int		/* flag to indicate user was dropped */
declare @threshcount int		/* count of thresholds bound by user */
declare @msg varchar(250)
declare @msg_all   varchar(100)		/* msg for "all" equivalent */
declare @msg_true  varchar(9)		/* msg for "true" equivalent */
declare @msg_false varchar(9)		/* msg for "false" equivalent */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((user_id() != 1) and (proc_role("sa_role") != 1))
	return(1)

/*
**  See if the user exists in the database.
**  User ids range from -16383 to +16383 and group ids are > 16383.
*/
select @uid = uid, @suid = suid
	from sysusers
		where name = @name_in_db
			and uid <= 16383 and uid != 0

/*
**  No such user so return.
*/
if @uid is NULL
begin
	/*
	** 17232, "No user with the specified name exists in the current database."
	*/
	exec sp_getmessage 17232, @msg output
	print @msg
	return (1)
end

/*
**  Big trouble if dbo (uid = 1) is dropped so check.
*/
if @uid = 1
begin
	/*
	** 17543, "You cannot drop the 'database owner'."
	*/
	exec sp_getmessage 17543, @msg output
	print @msg
	return (1)
end

/*
**  Trouble if guest gets dropped from master or tempdb, so check.
*/
if (@name_in_db = "guest" and (db_id() = 1 or db_id() = 2))
begin
	/*
	** 17544, "You cannot drop the 'guest' user from master or tempdb."
	*/
	exec sp_getmessage 17544, @msg output
	print @msg
	return(1)
end


/*
**  If the user owns any objects or datatypes and we're not
**  forcing the drop, return without doing anything.
*/
select @objectcount = count(*)
	   from sysobjects
		   where uid = @uid
select @typecount = count(*)
	from systypes
		where uid = @uid
select @grantcount = count(*)
	from sysprotects
		where grantor = @uid
			and id not in (select id from sysobjects
						where uid = @uid)
select @threshcount = count(*)
	from systhresholds
		where suid = @suid

if @objectcount > 0 or @typecount > 0 or @grantcount > 0 or @threshcount > 0
begin

	if @objectcount > 0
	begin
		/*
		** 17545, "You cannot drop user because user '%1!' owns objects in database."
		*/
		exec sp_getmessage 17545, @msg output
		print @msg, @name_in_db     
		select name, type
			from sysobjects
				where uid = @uid
	end

	if @typecount > 0
	begin
		/*
		** 17546, "You cannot drop user because user '%1!' owns types in database."
		*/
		exec sp_getmessage 17546, @msg output
		print @msg, @name_in_db
		select user_type = a.name, physical_type = b.name
			from systypes a, systypes b
				where a.uid = @uid
					and a.type = b.type
					and b.usertype < 100
	end

	if @grantcount > 0
	begin

		/*
		** 17431, "true"
		** 17432, "false"
		*/
		exec sp_getmessage 17431, @msg_true output
		exec sp_getmessage 17432, @msg_false output
		/* 17673, "All" */
		exec sp_getmessage 17673, @msg_all out

		/* create and populate temp tables so that we can map 
		** column bit map to names 
		*/
		create table #sysprotects1 (id int, uid smallint, 
					    action tinyint, protecttype tinyint,
					    grantor smallint, number int)

		create table #sysprotects2 (id int, col_count tinyint)

		insert into #sysprotects2 (id, col_count)
			select id, count (*)
			from syscolumns
			group by id

		insert into #sysprotects1 (id, uid, action, protecttype,
			grantor, number)
			select distinct
				p.id, p.uid, p.action, p.protecttype,
				p.grantor, c.number
				from sysprotects p, master.dbo.spt_values c
				where (~isnull (convert(tinyint, substring(p.columns, c.low, 1)), 0) & c.high != 0
					and c.number <= (select col_count from #sysprotects2 where id = p.id))
					and c.type = "P"
					and c.number <= 255
					and p.columns is not null
					and convert(tinyint, substring(p.columns, 1, 1)) & 0x1 != 0
					and (convert(tinyint, substring(p.columns, 1, 1)) & 0xfe != 0
						or substring(p.columns, 2, 1) is not null)

		insert into #sysprotects1 (id, uid, action, protecttype,
			grantor, number)
			select distinct
				p.id, p.uid, p.action, p.protecttype,
				p.grantor, c.number
				from sysprotects p, master.dbo.spt_values c
				where convert(tinyint, substring(isnull(p.columns, 0x1), c.low, 1))
					& c.high != 0
					and c.type = "P"
					and c.number <= 255
					and (p.columns is null
						or convert(tinyint, substring(p.columns, 1, 1)) & 0x1 = 0
						or (convert(tinyint, substring(p.columns, 1, 1)) & 0xfe = 0
							and substring(p.columns, 2, 1) is null))

		/* Set nocount on to avoid intermingling of output */
		set nocount on

		/*
		** 17549, "You cannot drop user because user '%1!' owns grantable
		**         privileges and granted them to other users.  The user
		** 	   has granted the following privileges:"
		*/
		exec sp_getmessage 17549, @msg output
		print @msg, @name_in_db
		print " "

		select grantee = u.name, 
			object = o.name, 
			column = substring(isnull(col_name(p.id, p.number), 
						  @msg_all), 1, 10),
			privilege = s.name
		from sysusers u, sysobjects o, #sysprotects1 p, 
		     master.dbo.spt_values s
		where p.grantor = @uid and p.uid = u.uid and p.protecttype < 2
	 	     and p.id = o.id and s.number = p.action 
		     and s.name is not NULL
		order by grantee, object, privilege

		/*
		** 18053, "User '%1!' was granted grantable privileges by the
		**         following users:"
		*/
		exec sp_getmessage 18053, @msg output
		print " "
		print @msg, @name_in_db
		
		select distinct grantor = u.name
		from sysusers u, sysprotects p
		where p.uid = @uid and u.uid = p.grantor and p.protecttype = 0
		order by grantor
	end

	if @threshcount > 0
	begin
		/*
		** 18033, "You cannot drop user because user '%1!' owns thresholds in database."
		*/
		exec sp_getmessage 18033, @msg output
		print @msg, @name_in_db     
		select "Segment name" = g.name, "Free pages" = t.free_space
			from syssegments g, systhresholds t
				where t.suid = @suid
				  and t.segment = g.segment
	end

	return (1)
end


/*
**  Drop the user.
**  Also drop any references to the user in the sysprotects table.
**  If anyone is aliased to the user, drop them also.
*/
begin transaction

	delete from sysusers
		where suid = @suid
	select @userdropped = @@rowcount




	delete from sysprotects
		where uid = @uid


	/*
	**  Drop any dependent aliases.
	*/
	if exists (select *
			from sysalternates
				where altsuid = @suid)
	begin
		delete from sysalternates
			where altsuid = @suid
		/*
		** 17547, "The dependent aliases were also dropped."
		*/
		exec sp_getmessage 17547, @msg output
		print @msg
	end

	/* 
	**  Delete entries from sysattributes
	*/
	delete from sysattributes
		where object_type = "U"
		and object = @uid

if @userdropped = 1
	commit transaction
else rollback transaction

/*
** 17548, "User has been dropped from current database."
*/
exec sp_getmessage 17548, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dropuser', 'anymode'
go
grant execute on sp_dropuser to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropremotelogin')
begin
	drop procedure sp_dropremotelogin
end
go
print "Installing sp_dropremotelogin"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_dropremotelogin"    17512
**
** 17260, "Can't run %1! from within a transaction." 
** 17512, "Remote login dropped."
** 17513, "There is no remote user '%1!' mapped to local user '%2!' from the remote server '%3!'."
*/

create procedure sp_dropremotelogin
@remoteserver	varchar(30),		/* name of remote server */
@loginame varchar(30) = NULL,		/* user's remote name */
@remotename varchar(30) = NULL		/* user's local user name */
as

declare	@msg	varchar(250)
declare @suid	smallint
declare @rname  varchar(30)
declare @lname  varchar(30)

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_dropremotelogin"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  If @loginame is NULL then we want to set @suid = -1. Otherwise get
**  it real value.
*/
if @loginame is null
	select @suid = -1
else select @suid = suser_id(@loginame)

/*
**  Delete the remote login.
*/
delete master.dbo.sysremotelogins
	from master.dbo.sysremotelogins l, master.dbo.sysservers s
	where l.remoteserverid = s.srvid
		and s.srvname = @remoteserver
		and l.remoteusername = @remotename
		and l.suid = @suid

/*
** Check @@rowcount when it works
*/
if @@rowcount > 0
begin
	/*
	** 17512, "Remote login dropped."
	*/
	exec sp_getmessage 17512, @msg output
	print @msg
	return (0)
end
else
begin
	/*
	** 17513, "There is no remote user '%1!' mapped to local user '%2!' from the remote server '%3!'."
	*/
	select @rname = isnull(@remotename, "NULL")
	select @lname = isnull(@loginame, "NULL")
	exec sp_getmessage 17513, @msg output
	print @msg, @rname, @lname, @remoteserver
	return (1)
end
go
exec sp_procxmode 'sp_dropremotelogin', 'anymode'
go
grant execute on sp_dropremotelogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropsegment')
begin
	drop procedure sp_dropsegment
end
go
print "Installing sp_dropsegment"
go

/* Sccsid = "@(#) generic/sproc/src/%M% %I% %G%" */

/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_dropsegment"        17520
**
** 17260, "Can't run %1! from within a transaction."
** 17281, "The specified device is not used by the database."
** 17520, "There is no such segment as '%1!'."
** 17521, "Can't drop the '%1!'segment completely."
** 17522, "The segment '%1!' is being used."
** 17523, "Segment '%1!' does not reference device '%2!'."
** 17524, "There is only one device mapping for the segment '%1!' -- use sp_dropsegment with no device argument."
** 17525, "Segment dropped."
** 17526, "Segment reference to device dropped."
** 17527, "WARNING: There are no longer any segments referencing device '%1!'.  This device will no longer be used for space allocation."
** 17528, "WARNING: There are no longer any segments referencing devices '%1!'.  These devices will no longer be used for space allocation."
** 17590, "The specified database does not exist." 
** 17715, "The last-chance threshold for database %1! is now %2! pages."
** 17716, "Could not update the last-chance threshold for database %1!"
** 17288, "You must execute this procedure from the database 
** 	  in which you wish to add a segment.  Please execute 
**	  'use %1!' and try again."
** 17289, "Set your curwrite to the hurdle of current database."
*/

create procedure sp_dropsegment
@segname	varchar(30),		/* segment name */
@dbname		varchar(30),	/* database name */
@device		varchar(30) = null	/* device name */
as

declare @dbuid	smallint	/* id of the owner of the database */
declare @dbid	smallint	/* id of the database */
declare @segbit	int		/* this is the bit to turn on in sysusages */
declare @lct	int		/* log's last-chance threshold setting */
declare	@msg	varchar(250)
declare	@procval int
select @procval = 0


/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_dropsegment"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/

if (user_id() = 1)
begin
	/* If user has sa role audit this as a successful sa 
	** command execution.
	*/ 
	if charindex("sa_role",show_role()) > 0
		select @procval = proc_role("sa_role") 
end
else 
begin
	/* user_id() is not DBO hence user does not have SA role
	** audit this as a failed sa command execution.
	*/
	select @procval = proc_role("sa_role")  
	return (1)
end

/*
**  There are two drop cases:
**	1) dropping the segment
**	2) dropping a segment reference to a device
**  The sproc does things differently depending on which we're doing.
*/

/*
**  Make ure the database exists
*/
if not exists ( select * from master.dbo.sysdatabases
		where name = @dbname )
begin
	/* 17590, "The specified database does not exist." */
	exec sp_getmessage 17590, @msg out
	print @msg
	return (1)
end

/*
**  Make sure that we are in the database specified
**  by @dbname. 
*/
if @dbname != db_name()
begin
	/* 
	** 17288, "You must execute this procedure from the database 
	** 	  in which you wish to add a segment.  Please execute 
	**	  'use %1!' and try again."
	*/
	exec sp_getmessage 17288, @msg out
	print @msg, @dbname
	return (1)
end

select @dbid = db_id(@dbname)

/*
**  Check to see if the segment exists.
*/
if not exists (select *
		from syssegments
			where name = @segname)
begin
	/*
	** 17520, "There is no such segment as '%1!'."
	*/
	exec sp_getmessage 17520, @msg output
	print @msg, @segname
	return (1)
end

/*
**  Get the segment number of @segname.
*/
select @segbit = segment
	from syssegments 
		where name = @segname

/*
**  Now convert the segment number to the right bit for segmap.
*/
if (@segbit < 31)
	select @segbit = power(2, @segbit)
else
	/*
	**  Since this is segment 31, power(2, 31) will overflow
	**  since segmap is an int.  We'll grab the machine-dependent
	**  bit mask from spt_values to clear the right bit.
	*/
	select @segbit = low
		from master.dbo.spt_values
			where type = "E"
				and number = 2

/*
**  Don't allow the segments 'default', 'system', or 'logsegment' to
**  be dropped completely.
*/
if @segname in ("system", "default", "logsegment")
begin
	if @device is null
	begin
		/*
		** 17521, "Can't drop the '%1!'segment completely."
		*/
		exec sp_getmessage 17521, @msg output
		print @msg, @segname
		return (1)
	end

	/*
	**  For the case where we are dropping the logsegment from a 
	**  device, the logic below works OK.  If this is the last
	**  device for the the segment, it won't let the segment be
	**  dropped.
	*/
end


/*
**  If we are dropping the segment, check to see that the segment isn't
**  being used by anyone.
*/
if @device is null
begin

	/*
	**  Check to see if the segment is being used.
	*/
	if exists (select *
			from sysindexes i, syssegments s
				where s.name = @segname
					and i.segment = s.segment)
	begin
		/*
		** 17522, "The segment '%1!' is being used."
		*/
		exec sp_getmessage 17522, @msg output
		print @msg, @segname
		return (1)
	end
end

/*
**  If we are dropping the segment reference, check to see that arguments are
**  reasonable.
*/
if @device is not  null
begin
	/*
	**  Now see if the database even uses the @device
	*/
	if not exists (select *
			from master.dbo.sysusages u, master.dbo.sysdevices d
				where d.name = @device
					and u.vstart between d.low and d.high
					and u.dbid = @dbid)
	begin
		/*
		** 17281, "The specified device is not used by the database."
		*/
		exec sp_getmessage 17281, @msg output
		print @msg
		return (1)
	end

	/*
	**  Now check that the segment references the device.
	*/
	if not exists (select *
			from master.dbo.sysusages u, master.dbo.sysdevices d
				where u.segmap & @segbit = @segbit
				and d.name = @device
				and d.low <= u.size + u.vstart
				and d.high >= u.size + u.vstart - 1 
				and u.dbid = @dbid
				and d.status & 2 = 2)
	begin
		/*
		** 17523, "Segment '%1!' does not reference device '%2!'."
		*/
		exec sp_getmessage 17523, @msg output
		print @msg, @segname, @device
		return (1)
	end

	/*
        **  Now check to see if this is the last unique device reference for the
	**  segment.  If it is then we don't want to drop the reference.
	*/
        select distinct d.name into #temptable
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where u.segmap & @segbit = @segbit
				and d.low <= u.size + u.vstart
				and d.high >= u.size + u.vstart - 1
				and u.dbid = @dbid
                                and d.status & 2 = 2

        if (select count(*) from #temptable) <= 1
	begin
		/*
		** 17524, "There is only one device mapping for the segment '%1!' -- use sp_dropsegment with no device argument."
		*/
		exec sp_getmessage 17524, @msg output
		print @msg, @segname
		return (1)
	end

        drop table #temptable
end

/*
**  If we're dropping the segment, go ahead drop the segment and
**  clear its bit in sysusages.
*/
if @device is null
begin


	/*
	**  Remove any threshold references
	*/
	if exists (select * from sysobjects where name = "systhresholds")
		delete systhresholds
		from systhresholds t, syssegments s
		where	s.name = @segname
		  and	s.segment = t.segment

	/*
	**  NOTE: Don't update master.dbo.sysusages and syssegments as a xact 
	**  	since it could cause problems for recovery.
	*/



	delete syssegments
		where name = @segname


	/*
	**  Now clear the segment from device in sysusages.
	*/
	update master.dbo.sysusages
		set segmap = segmap & (~@segbit)
			from master.dbo.sysusages u, master.dbo.sysdevices d
				where d.low <= u.size + u.vstart
					and d.high >= u.size + u.vstart - 1
					and u.dbid = @dbid
					and d.status & 2 = 2
end

/*
**  We want to just clear the segment reference from the device.
*/
else
begin


	update master.dbo.sysusages
		set segmap = segmap & (~@segbit)
			from master.dbo.sysusages u, master.dbo.sysdevices d
				where d.low <= u.size + u.vstart
					and d.high >= u.size + u.vstart - 1
					and u.dbid = @dbid
					and d.status & 2 = 2
					and d.name = @device

	/*
	**  Remove any threshold references that exceed the remaining
	**  size of the segment
	*/
	if exists (select * from sysobjects where name = "systhresholds")
		delete systhresholds
		from systhresholds t, syssegments s
		where	s.name = @segname
		  and	s.segment = t.segment
		  and	t.free_space >= (select sum(size)
					 from master.dbo.sysusages
					 where dbid = @dbid
					   and segmap & @segbit = @segbit)
end

/*
**  Now we need to activate the new segment map.
*/
dbcc dbrepair (@dbname, remap)

/*
** If we are removing log space, we may have cleared a stranded-object
** condition, so we need to look for stranded objects.  We can also take
** this opportunity to recalculate the log's last-chance threshold.
*/
if @segbit = 4
begin
	dbcc dbrepair (@dbname, findstranded)
	select @lct = lct_admin("lastchance", @dbid)
	if @lct > 0
		exec sp_getmessage 17715, @msg out
	else
		exec sp_getmessage 17716, @msg out
	print @msg, @dbname, @lct
end


if @device is null
begin
	/*
	** 17525, "Segment dropped."
	*/
	exec sp_getmessage 17525, @msg output
	print @msg
end
else 
begin
	/*
	** 17526, "Segment reference to device dropped."
	*/
	exec sp_getmessage 17526, @msg output
	print @msg
end

/*
**  If there are no more segment references to the device,
**  print a warning.
*/
if exists (select *
		from master.dbo.sysusages
			where segmap = 0
				and dbid = @dbid)
begin
	declare @nosegs	varchar(255),	/* list of unreferenced devices */
		@curdevice	varchar(30),
		@i	int
	
	select @curdevice = min(d.name)
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.low <= u.size + u.vstart
				and d.high >= u.size + u.vstart - 1
				and u.dbid = @dbid
				and d.status & 2 = 2
				and segmap = 0
	select @nosegs = @curdevice, @i = 1
	while (@curdevice is not  null)
	begin
		select @curdevice = min(d.name)
			from master.dbo.sysusages u, master.dbo.sysdevices d
				where d.low <= u.size + u.vstart
					and d.high >= u.size + u.vstart - 1
					and u.dbid = @dbid
					and d.status & 2 = 2
					and segmap = 0
					and d.name > @curdevice
		if @curdevice is not  null
		begin
			select @nosegs = @nosegs + ", " + @curdevice
			select @i = @i + 1
		end
	end

	/*
	**  Get the device names.
	*/
	if @i > 1
		/*
		** 17528, "WARNING: There are no longer any segments referencing devices '%1!'.  These devices will no longer be used for space allocation."
		*/
		exec sp_getmessage 17528, @msg output
	else 
		/*
		** 17527, "WARNING: There are no longer any segments referencing device '%1!'.  This device will no longer be used for space allocation."
		*/
		exec sp_getmessage 17527, @msg output
	print @msg, @nosegs
end
return (0)
go
exec sp_procxmode 'sp_dropsegment', 'anymode'
go
grant execute on sp_dropsegment to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropserver')
begin
	drop procedure sp_dropserver
end
go
print "Installing sp_dropserver"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
** Messages for "sp_dropserver"         17530
**
** 17260, "Can't run %1! from within a transaction." 
** 17270, "There is not a server named '%1!'."
** 17530, "There are still remote logins for the server '%1!'."
** 17531, "Remote logins for remote server '%1!' have been dropped."
** 17532, "Usage: sp_dropserver server [, droplogins]"
** 17533, "Server dropped."
*/

create procedure sp_dropserver
@server	varchar(30),			/* server name */
@droplogins	char(10) = NULL		/* drop all related logins? */
as

declare	@msg	varchar(200)

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_dropserver"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sso role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sso_role") = 0)
	return (1)

/*
**  Check to see if the server exists.
*/
if not exists (select *
		from master.dbo.sysservers
			where srvname = @server)
begin
	/*
	** 17270, "There is not a server named '%1!'."
	*/
	exec sp_getmessage 17270, @msg output
	print @msg, @server
	return (1)
end

/*
**  Check to see if there are any related logins in sysremotelogins.
*/
if @droplogins is NULL
begin
	if exists (select *
			from master.dbo.sysremotelogins l,
				master.dbo.sysservers s
			where s.srvid = l.remoteserverid
				and s.srvname = @server)
	begin
		/*
		** 17530, "There are still remote logins for the server '%1!'."
		*/
		exec sp_getmessage 17530, @msg output
		print @msg, @server
		return (1)
	end
end

/*
**  If @droplogins is true then drop any associated logins
*/
else if @droplogins = "droplogins"
begin
	begin transaction dropserver

		delete master.dbo.sysremotelogins
			from master.dbo.sysremotelogins l,
				master.dbo.sysservers s
			where s.srvid = l.remoteserverid
				and s.srvname = @server
		if @@rowcount > 0
		begin
			/*
			** 17531, "Remote logins for remote server '%1!' have been dropped."
			*/
			exec sp_getmessage 17531, @msg output
			print @msg, @server
		end

		/*
		** Hang up the connection to the server if there is one
		*/
		dbcc connection_hangup(@server)		

		delete master.dbo.sysservers
			where srvname = @server

		/*
		** 17533, "Server dropped."
		*/
		exec sp_getmessage 17533, @msg output
		print @msg

	commit transaction dropserver

	return (0)
end

/*
**  Bad argument to @droplogins.
*/
else
begin
	/*
	** 17532, "Usage: sp_dropserver server [, droplogins]"
	*/
	exec sp_getmessage 17532, @msg output
	print @msg
	return (1)
end

/*
** Hang up the connection to the server if there is one
*/
dbcc connection_hangup(@server)		

/*
**  Drop the server.
*/
delete master.dbo.sysservers
	where srvname = @server

/*
** 17533, "Server dropped."
*/
exec sp_getmessage 17533, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_dropserver', 'anymode'
go
grant execute on sp_dropserver to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_estspace')
begin
	drop procedure sp_estspace
end
go
print "Installing sp_estspace"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*
** Messages for "sp_estspace"
** 17461, "Object does not exist in this database."
** 18054, "Table contains text/image type columns but length for these columns not specified in the argument list.
*/

create procedure sp_estspace

/*	A procedure to estimate the disk space requirements of a table
**	and its associated indexes
**	Written by Malcolm Colton with assistance from Hal Spitz
*/
	(@table_name	varchar(30)=null, /* name of table to estimate */
	 @no_of_rows	float = 0,	  /* number of rows in the table */
	 @fill_factor	float = null,	/* the fill factor */
	 @cols_to_max	varchar(255) =null, /* variable length columns for which
					to use the maximum rather than 50% of 
					the maximum length 	*/
	 @textbin_len  float = null, /* len of all text & binary data/row */
	 @iosec		float = 30)
as

declare @msg	varchar(120)

if @@trancount = 0
begin
        set chained off
end

set transaction isolation level 1

/*	Give usage statement if @table_name is null */

if @table_name is null or @no_of_rows <= 0 or @fill_factor < 1 or @fill_factor > 100 
begin
	print 'USAGE:'
	print 'sp_estspace table_name, no_of_rows, fill_factor, cols_to_max, textbin_len, iosec'
	print 'where '
	print '      table_name  is the name of the table,'
	print '      no_of_rows  is the number of rows in the table (>0),' 
	print '      fill_factor is the index fill factor. Values range from' 
	print '                   1 to 100. (default = 0,in which case internal'
	print '                   fill factor will be used)' 
	print '      cols_to_max is a list of the variable length columns for which'
	print '                   to use the maximum length instead of the average'
	print '			  (default = null)'
	print '      textbin_len is length of all the text and binary fields per'
	print '                   row ( default =  0).' 
	print '      iosec       is the number of I/Os per second on this machine'
	print '                   (default = 30)'
	print 'Examples: sp_estspace titles, 10000, 50, "title, notes", null, 25'
	print '          sp_estspace titles, 50000'
	print '          sp_estspace titles, 50000, null, null, null, 40'
	return
end

declare	@sum_fixed	int,
	@sum_var	int,
	@sum_avgvar	int,
	@table_id	int,
	@num_var	int,
	@data_pages	float,
	@sysstat	smallint,
	@temp		float,
	@temp1		float,
	@index_id	int,
	@last_id	int,
	@i		int,
	@level_pages	float,
	@key		varchar(30),
	@usertype	tinyint,
	@type		tinyint,
	@level		smallint,
	@vartype	smallint,
	@more		bit,
	@next_level	float,
	@rows_per_page	smallint,
	@row_len	int,
	@length		tinyint,
	@index_name	varchar(30),
	@page_size	smallint,
	@page_K		tinyint,
	@index_type	varchar(20),
	@mrpg		smallint,
	@factor		float

select	@sum_fixed=0,
	@sum_var=0,
	@sum_avgvar=0,	
	@table_id=0,
	@num_var=0,
	@data_pages=0,
	@row_len=0,
	@sysstat=0,
	@iosec = 30	/* iosec==the expected number of 512byte I/O per sec */

set nocount on

/* set the default fill_factor */
if @fill_factor is null
	select @fill_factor = 0 

/* Make sure table exists */

select  @sysstat = sysstat,
	@table_id = id
		from sysobjects where name = @table_name

if @sysstat & 7 not in (1,3)
begin
	/* 17461, "Object does not exist in this database." */
	exec sp_getmessage 17461, @msg out
	print @msg
	return  (1)
end

/* Get machine page size */

select 	@page_size = low - 32
	from master.dbo.spt_values
		where type = 'E'
		and number = 1

select @page_K = (@page_size +32) /1024

if @fill_factor !=0
	select @fill_factor = @fill_factor / 100.0

/* Get the max_rows_per_page value */
select @mrpg = maxrowsperpage
	from sysindexes
		where id=@table_id and indid in (0,1)

/* Create tables for results */

create table #results
	(name	varchar(30),
	 type	varchar(12),
	 idx_level	smallint,
	 pages	float,
	 Kbytes float)

create table #times
	(name 		varchar(30),
	 type	 	varchar(12) null,
	 tot_pages	float null,
	 time_mins	float 	null)


/* Create table of column info for the table to be estimated */ 

select length, type, name
	into #col_table
		from syscolumns
			where id = @table_id


/* check if text/image lenth specified if these fields exist in the table */
if ( @textbin_len is null )
begin
	if exists( select name from syscolumns where id = @table_id and
			(type = 35 or type = 34 ))
	
	begin
		exec sp_getmessage 18054, @msg out
		print @msg
		return  (1)
	end
end
	
	
/* Look up the important values from this table */

select @sum_fixed = isnull(sum(length),0)
	from #col_table
		where type != 39

select @num_var = isnull(count(*),0), @sum_var = isnull(sum(length),0)
	from #col_table
		where type = 39
			and charindex(name, @cols_to_max) > 0

select @num_var = @num_var + isnull(count(*),0), 
       @sum_avgvar = isnull(sum(length / 2),0)
	from #col_table
		where type = 39
			and charindex(name, @cols_to_max) = 0
/* Calculate the data page requirements */

set arithabort numeric_truncation off

if @num_var = 0
	select @row_len = 4.0 + @sum_fixed
else
begin
	select @row_len = 8.0 + @sum_fixed + @sum_var +@sum_avgvar + @num_var
				+ (@sum_fixed +@sum_var) / 256.0
end


/* Allow for fill-factor if set to other than zero */

if @fill_factor = 0	
begin
	select @temp = convert(float, @no_of_rows) * 
		( convert(float, @row_len) / convert(float, @page_size) )
end
else
begin
	select @temp = convert(float, @no_of_rows) / 
		(convert(float, @page_size) * convert(float, @fill_factor) )
	select @temp = convert(float, @row_len) * @temp
end

/* 
** If there is maxrowsperpage and it creates less number of pages than
** without it, then use it.
*/
if @mrpg != 0
begin
	select @temp1 = convert(float, @no_of_rows) /
				convert(float, @mrpg)
	if @temp < @temp1
		select @temp = @temp1
end

/* Now add in allocation pages */
select @temp = @temp +(@temp / 64260.0)
select @data_pages = @temp + 1.0
if @data_pages < 8.0
	select @data_pages = 8.0

insert #results values 
	(@table_name, 'data', 0, @data_pages, @data_pages * @page_K)

/* calculate the pages for text and length */

/* text/bin pages write multiples of 450 bytes per page */
if ( @textbin_len is not  null )
begin
	select @temp = ceiling( @textbin_len/ (floor(@page_size/450.0)*450.0))
	select @temp = @temp * @no_of_rows
	insert #results values 
		(@table_name, 'text/image', 0, @temp, @temp * @page_K)
end

/* See if the table has any indexes */

select @index_id = min(indid)
	from sysindexes 
		where id = @table_id
			and indid > 0 and indid < 255

if @index_id is null	/* We've finished if there are no indexes */
begin
	select @msg = @table_name + ' has no indexes'
	print @msg
	select name, type, idx_level, 
		Pages = str(pages,12,0), Kbytes = str(Kbytes,12,0) 
		from #results

	select Total_Mbytes = str(sum(Kbytes)/1024.0,17,2)
		from #results

	drop table #results
	return
end

select 	@sum_fixed = 0,
	@sum_var = 0,
	@num_var = 0,
	@temp = 0

/* For each index, calculate the important variables
** use them to calculate the index size, and print it */

while @index_id is not  null
begin
	select @index_name = name , @mrpg = maxrowsperpage
		from sysindexes
			where id = @table_id
			and indid = @index_id
	if @index_id = 1
		select @index_type = 'clustered'
	else
		select @index_type = 'nonclustered'

	select 	@num_var = 0,
		@sum_var = 0,
		@sum_fixed = 0

	select @i = 1

	/* Look up each of the key fields for the index */

	while @i <= 16
	begin
		select @key = index_col(@table_name, @index_id, @i)

		if @key is null
			break
		else			/* Process one key field */
		begin
			select @type = type, @length = length, @vartype = offset
				from syscolumns
					where id = @table_id
					and name = @key

			if @vartype < 0
				select @num_var = @num_var + 1
			else
				select @sum_fixed = @sum_fixed + @length

			if @type = 39	/* varchar: check if in @cols_to_max */ 
			begin
				if charindex(@key, @cols_to_max) = 0
				   select @sum_var = @sum_var + (@length / 2)
				else
				   select @sum_var = @sum_var + @length
			end
		end

		select @i = @i + 1	/* Get next key field in this index */
	end

	/* Calculate the space used by this index */

	if @index_id = 1
	begin
		if @num_var = 0
			select @row_len = 5 + @sum_fixed
		else
			select @row_len = @sum_fixed + @sum_var + @num_var + 8
	end
	else
	begin
		if @num_var = 0
			select @row_len = 7 + @sum_fixed
		else
			select @row_len = @sum_fixed + @sum_var + @num_var + 11
	end

	select @level = 0

	/* Allow for fill-factor if set to other than zero */

	if @fill_factor = 0 or @index_id = 1
	begin
		select @rows_per_page =  @page_size / @row_len - 2
	end
	else
	begin
		select @rows_per_page = @page_size / @row_len * @fill_factor 
	end

	if @rows_per_page > 256
		select @rows_per_page = 256

	/* at lease one row per page */
	if @rows_per_page < 1
		select @rows_per_page = 1

	/* For clustered indexes, the first level of index is based on the 
	** number of data pages. 
	** For nonclustered, it is the number of data rows	*/

	if @index_id = 1
		select @next_level = @data_pages
	else
		select @next_level = @no_of_rows
	select @more = 1	/* Flag for end of index levels */
	while @more = 1
	begin
		if @index_id != 1 and @level = 0  and @mrpg != 0
			select @rows_per_page = @mrpg

		/* No fill factor for non-leaf nodes, recalculate rows/page */
		if @index_id != 1 and @level = 1 
		begin
			select @row_len = @row_len + 4 
			select @rows_per_page = @page_size/@row_len - 2
			if @rows_per_page > 256
				select @rows_per_page = 256
		end

		/* calculate the number of pages at a single index level */
		select @temp = @next_level / convert(float, @rows_per_page)

		/* Add in a factor for allocation pages */
		select @temp = @temp + (@temp /64260.0) + 1.0
		
		select @level_pages = @temp
		
		insert #results values
			(@index_name, @index_type, @level, @level_pages, 
				convert(int, @level_pages) * @page_K)
		
		select @next_level = @level_pages
		select @level = @level + 1

		/* see if we can fit the next level in 1 page */
		if @rows_per_page >= @next_level 
			select @more = 0
	end
	/* Account for single root page */
	if @level_pages > 1
		insert #results values
			(@index_name, @index_type, @level, 1, @page_K)

	/* Now look for next index id for this table */

	select @last_id = @index_id
	select @index_id = null
	select @index_id = min(indid)
		from sysindexes 
			where id = @table_id
			and indid > @last_id
			and indid < 255

end
select name, type, idx_level, Pages = str(pages,12,0), Kbytes = str(Kbytes,12,0) 
from #results

select Total_Mbytes = str(sum(Kbytes)/1024.0,17,2)
from #results

/* Get ready to calculate creation times for the indexes */

insert #times (name, tot_pages)
	select name, sum(pages) 
	from #results
	where type != 'data'
	group by name

/* Get index type from #results */
update #times
	set #times.type = #results.type
	from #times, #results
	where #times.name = #results.name

/* Add data pages to size of clustered index */
update #times
	set tot_pages=tot_pages + @data_pages
	where type = 'clustered'

/* Calculate for clustered index */

select @factor = ceiling( (log(@data_pages) / 2.07944) - 1.8813 )
update #times
	set time_mins = ( (2 * @factor) + 1) * @data_pages / 60 / @iosec
	where type = 'clustered'

/* Calculate for non-clustered index */

update #times
	set time_mins = ( (2 * @factor * tot_pages) + @data_pages )
		/ 60 / @iosec
	where time_mins is null

select name, type, total_pages=str(tot_pages,12,0), 
	time_mins=str(time_mins,12,0)
from #times

drop table #results
drop table #col_table
drop table #times

return
go
exec sp_procxmode 'sp_estspace', 'anymode'
go
grant execute on sp_estspace to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_extendsegment')
begin
	drop procedure sp_extendsegment
end
go
print "Installing sp_extendsegment"
go

/* Sccsid = "@(#) generic/sproc/src/%M% %I% %G%" */
/*	5.0	14.2	11/12/91	sproc/src/extendsegment */

/*
** Messages for "sp_extendsegment"      17550
**
** 17260, "Can't run %1! from within a transaction."
** 17284, "'%1!' is not a valid identifier."
** 17520, "There is no such segment as '%1!'."
** 17281, "The specified device is not used by the database."
** 17283, "'%1!' is reserved exclusively as a log device."
** 17280, "No such device exists -- run sp_helpdb to list the devices for the current database."
** 17550, "Segment extended."
** 17551, "Device '%1!' is now exclusively used by '%2!'"
** 17715, "The last-chance threshold for database %1! is now %2! pages."
** 17716, "Could not update the last-chance threshold for database %1!"
** 17552, "This command has been ignored.  Extending the log segment on device '%1!' would leave no space for creating objects in database '%2!'."
** 17590, "The specified database does not exist." 
** 17288, "You must execute this procedure from the database 
** 	  in which you wish to add a segment.  Please execute 
**	  'use %1!' and try again."
** 17289, "Set your curwrite to the hurdle of current database."
*/

create procedure sp_extendsegment
@segname	varchar(30),	/* segment name */
@dbname		varchar(30),	/* database name */
@devname	varchar(30)	/* device name to put segment on */
as

declare @dbuid	smallint	/* id of the owner of the database */
declare @dbid	smallint	/* id of the database */
declare @segbit	int		/* this is the bit to turn on in sysusages */
declare @lct	int		/* log new last-chance threshold value */
declare	@msg	varchar(250)
declare @new_msg varchar(100)
declare @returncode int
declare @procval int

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
 	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_extendsegment"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  if user  had SA role he would be the dbo hence check only
**  whether user is DBO.
*/
if (user_id() = 1)
begin
        /* If user has sa role audit this as a successful sa
        ** command execution.
        */
        if charindex("sa_role",show_role()) > 0
                select @procval = proc_role("sa_role")
end
else
begin
        /* user_id() is not DBO hence user does not have SA role
        ** audit this as a failed sa command execution.
        */
        select @procval = proc_role("sa_role")
        return (1)
end

/*
**  Make ure the database exists
*/
if not exists ( select * from master.dbo.sysdatabases
		where name = @dbname )
begin
	/* 17590, "The specified database does not exist." */
	exec sp_getmessage 17590, @msg out
	print @msg
	return (1)
end

/*
**  Make sure that we are in the database specified
**  by @dbname. 
*/
if @dbname != db_name()
begin
	/* 
	** 17288, "You must execute this procedure from the database 
	** 	  in which you wish to add a segment.  Please execute 
	**	  'use %1!' and try again."
	*/
	exec sp_getmessage 17288, @msg out
	print @msg, @dbname
	return (1)
end

select @dbid = db_id(@dbname)

/*
**  Check to see if the segment exists.
*/
if not exists (select *
		from syssegments
			where name = @segname)
begin
	/*
	** 17520, "There is no such segment as '%1!'."
	*/
	exec sp_getmessage 17520, @msg output
        print @msg, @segname
	return (1)
end

/*
**  See if the device exists.
*/
if not exists (select *
		from master.dbo.sysdevices
			where name like @devname)
begin
	/*
	** 17280, "No such device exists -- run sp_helpdb to list the devices for the current database."

	*/
	exec sp_getmessage 17280, @msg output
        print @msg
	return (1)
end

/*
**  Now see if the @dbname uses the @devname
*/

if not exists (select *
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = @dbid)
begin
	/*
	** 17281, "The specified device is not used by the database."
	*/
	exec sp_getmessage 17281, @msg output
        print @msg
	return (1)
end

/*
**  Check to see if the device is marked as a log device.
**  If so, print error.
*/
if exists (select *
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = @dbid
				and segmap = 4)
begin
	/*
	** 17283, "'%1!' is reserved exclusively as a log device."
	*/
	exec sp_getmessage 17283, @msg output
        print @msg, @devname
	return (1)
end

/*
**  Get the segment number for @segname.
*/
select @segbit = segment
	from syssegments
		where name = @segname



/*
**  If @segbit is 2 then it's the logsegment and the logsegment
**  doesn't share devices with other segments.  In this case,
**  don't OR the @segbit in but just set segmap to 4.
*/
if @segbit = 2
begin
	/*
	** Extending the logsegment means we won't be able to
	** create any more objects on this device. (See comment above.)
	** Do it only if non-log space is available on other devices.
	*/
	if not exists (select *
		from master.dbo.sysdevices d,
			master.dbo.sysusages u
		where u.vstart between d.low and d.high
			and u.dbid = @dbid
			and u.segmap != 4
			and d.name != @devname
			and d.cntrltype = 0)
	begin
		/*
		** 17552, "This command has been ignored.  Extending the log
		** segment on device '%1!' would leave no space for creating
		** objects in database '%2!'."
		*/
		exec sp_getmessage 17552, @msg output
		print @msg, @devname, @dbname
		return (1)
	end

	update master.dbo.sysusages
		set segmap = 4
			from master.dbo.sysusages u,
				master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = @dbid
end

else
begin
	if (@segbit < 31)
		select @segbit = power(2, @segbit)
	else
		/*
		**  Since this is segment 31, power(2, 31) will
		**  overflow since segmap is an int.  We'll grab the
		**  machine-dependent bit mask from spt_values to set
		**  the right bit.
		*/
		select @segbit = low
			from master.dbo.spt_values
				where type = "E"
					and number = 2
	/*
	**  Add the segment to @devname in sysusages.
	*/
	update master.dbo.sysusages
		set segmap = segmap | @segbit
			from master.dbo.sysusages u,
				master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = @dbid
end

/*
**  Get the segment number for @segname.
*/
select @segbit = segment
	from syssegments
		where name = @segname

/*
** If we are adding log space, we might be going onto a segment that
** used to contain user data, so we need to look for stranded objects.
*/
if @segbit = 2
	dbcc dbrepair (@dbname, findstranded)

/*
**  Now we need to activate the new segment map.
*/
dbcc dbrepair (@dbname, remap)

/*
** Now that dbrepair has remapped the database, we can
** recalculate the log's last-chance threshold.
*/
if @segbit = 2
begin
	select @lct = lct_admin("lastchance", @dbid)
	if @lct > 0
		exec sp_getmessage 17715, @msg out
	else
		exec sp_getmessage 17716, @msg out
	print @msg, @dbname, @lct
end

/*
** 17550, "Segment extended."
*/
exec sp_getmessage 17550, @msg output
print @msg

/*
**  If we are extending the logsegment, print out a message about what it
**  means to do so.
*/
if @segbit = 2
begin
	/*
	** 17551, "Device '%1!' is now exclusively used by '%2!'"
	*/
	exec sp_getmessage 17551, @msg output
        print @msg, @devname, @segname
end

return (0)
go
exec sp_procxmode 'sp_extendsegment', 'anymode'
go
grant execute on sp_extendsegment to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_fixindex')
begin
	drop procedure sp_fixindex
end
go
print "Installing sp_fixindex"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */


create procedure sp_fixindex
		@dbname		varchar(30),
		@tabname	varchar(30),  		/* system table name */
		@indid		int			/* index id value    */
as
	/*
	**	Description:	allow the SA to force a drop and then a
	**			create index on system catalogs.
	**
	**	Usage:		sp_fixindex  database, systemcatalog, ind_id
	**
	**	History:	3/28/88		(robbie)
	*/

	declare	@ramboix smallint			/* mask for rambo indx*/
	declare @badlist  varchar(255)   /* name list of all tables that should
					      not have any indexes on them */

	declare @msg varchar(255)

	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	/* check if user has SA role, proc_role will also do auditing
	** if required. proc_role will also print error message if required.
	*/

        if (proc_role("sa_role") = 0)
                return (1)

	/*
	**	Initialize name lists. These will be used in catching
	**	any attempts to fix indexes on fake tables or tables
	**	that have no indexes on them.
	*/
	select @badlist = "syslocks, sysprocesses, syscurconfig, 
			   syssegments, sysindexes"

	/*
	**	Make sure we are "fixing" a system catalog.
	*/
	if @tabname NOT LIKE  "sys%"
	begin
		/*
		** 18055: "Procedure should be used on system tables only."
		*/
		exec sp_getmessage 18055, @msg output
		print @msg
		return (1)
	end

	/*
	**	Make sure that we are doing this on somenthing that 
	**	has indexes (or real tables).
	*/
	if @badlist LIKE  "%" + @tabname + "%"
	begin
		/*
		** 18056: "Cannot re-create index on this table."
		*/
		exec sp_getmessage 18056, @msg output
		print @msg
		return (1)
	end

	/*
	**	Make sure that we can not re-create index 
	**	on index of id 1 on sysobjects.
	*/
	if ((@tabname = "sysobjects" and @indid = 1))
	begin
		/*
		** 18057: "The index with id 1 on sysobjects can not be 
		** recreated."
		*/
		exec sp_getmessage 18057, @msg output
		print @msg
		return (1)
	end

	/*
	**	At this point we are sure that the table has an index
	**	of requested type, so all there is to be done is to
	**	set the ramboix bit for this object.
	**	NB: we have explicitly disallowed sysobjects, index id 1
	**	    above.
	*/
	select @ramboix = 4096
	update sysobjects set sysstat = sysstat | @ramboix
	where name = @tabname

	checkpoint

	/*
	**	Call dbcc to do the job.
	*/
	dbcc dbrepair(@dbname, REPAIRINDEX, @tabname, @indid)

	/*
	**	Processing successfully done, so turn off the ramboix
	**	bit if not sysobjects, and tell the user that all is fine.
	*/
	if @tabname != "sysobjects"
	begin
		update sysobjects set sysstat = sysstat & ~@ramboix
		where name = @tabname
	 
		checkpoint
	end

	return (0)
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_fkeys')
begin
	drop procedure sp_fkeys
end
go
print "Installing sp_fkeys"
go

/* sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*
** note: there is one raiserror message: 18040
**
** messages for "sp_fkeys"               18039, 18040
**
** 17461, "Object does not exist in this database." 
** 18040, "Catalog procedure %1! can not be run in a transaction.", sp_fkeys
** 18043 " Primary key table name or foreign key table name or both must be 
** given"
** 18044, "%1! table qualifier must be name of current database." [Primary
** key | Foreign key]
**
*/
CREATE PROCEDURE sp_fkeys
			   @pktable_name		varchar(32) = null,
			   @pktable_owner		varchar(32) = null,
			   @pktable_qualifier	varchar(32) = null,
			   @fktable_name		varchar(32) = null,
			   @fktable_owner		varchar(32) = null,
			   @fktable_qualifier	varchar(32) = null 
as
declare @ftabid int, @ptabid int, @keycnt int, @i int
declare @fokey1 int,  @fokey2 int,  @fokey3 int,  @fokey4 int,  @fokey5  int
declare @fokey6 int,  @fokey7 int,  @fokey8 int,  @fokey9 int,  @fokey10 int
declare @fokey11 int, @fokey12 int, @fokey13 int, @fokey14 int, @fokey15 int
declare @refkey1 int, @refkey2 int, @refkey3 int, @refkey4 int, @refkey5  int
declare @refkey6 int, @refkey7 int, @refkey8 int, @refkey9 int, @refkey10 int
declare @refkey11 int, @refkey12 int, @refkey13 int, @refkey14 int
declare @refkey15 int, @refkey16 int, @fokey16 int, @status int
declare @msg varchar(255)
declare @msg2 varchar(50)

	set nocount on

	if (@@trancount = 0)
	begin
		set chained off
	end
	else
	begin
		/* if inside a transaction */
		/* catalog procedure sp_fkeys can not be run in a transaction.*/
		exec sp_getmessage 18040, @msg output
		raiserror 18040 @msg, "sp_fkeys"
		return (1)
	end

	set transaction isolation level 1

	if (@pktable_name is null) and (@fktable_name is null)
	begin	
		/* If neither primary key nor foreign key table names given */
		/* 
		** 18043 "Primary key table name or foreign key table name 
		** or both must be given"
		*/
		exec  sp_getmessage 18043, @msg output
		print @msg
		return (1)
	end

	if @fktable_qualifier is not null
	begin
		if db_name() != @fktable_qualifier
		begin	
			/* If qualifier doesn't match current database */
			/* 18044 "Foreign Key Table qualifier must be name 
			** of current database"
			*/
			exec sp_getmessage 18044, @msg output
			exec sp_getmessage 18050, @msg2 output
			print @msg, @msg2
			return (1)
		end
	end
	else
	begin
		/*
		** Now make sure that foreign table qualifier is pointing to the
		** current database in case it is not specified.
		*/
		select @fktable_qualifier = db_name()
	end

	if @pktable_qualifier is not null
	begin
		if db_name() != @pktable_qualifier
		begin	
			/* If qualifier doesn't match current database */
			/* 18044 "Primary Key Table qualifier must be name 
			** of current database"
			*/
			exec sp_getmessage 18044, @msg output
			exec sp_getmessage 18051, @msg2 output
			print @msg, @msg2
			return (1)
		end
	end
	else
	begin
		/*
		** Now make sure that primary table qualifier is pointing to the
		** current database in case it is not specified.
		*/
		select @pktable_qualifier = db_name()
	end


	create table #pid (pid int, uid smallint, name varchar(30))
	create table #fid (fid int, uid smallint, name varchar(30))

	if @pktable_name is not null
	begin 
		if (@pktable_owner is null)
		begin
			/* 
			** owner is NULL, so default to the current user
			** who owns this table, otherwise default to dbo
			** who owns this table.
			*/
			insert into #pid 
			select id, uid, name
			from sysobjects 
			where name = @pktable_name and uid = user_id()
			and type in ("S", "U")
			
			/* 
			** If the current user does not own the table, see
			** if the DBO of the current database owns the table.
			*/

			if ((select count(*) from #pid ) = 0)
			begin
				insert into #pid 
				select id, uid, name
				from sysobjects 
				where name = @pktable_name and uid = 1
				and type in ("S", "U")
			end
		end
		else
		begin
			insert into #pid
			select id, uid, name
			from sysobjects
			where name = @pktable_name 
			and uid = user_id(@pktable_owner)
			and type in ("S", "U")
		end
	end
	else 
	begin
		if (@pktable_owner is null)
		begin
		/* 
		** If neither pktable_name nor pktable_owner is specified,
		** then we are interested in every user or system table.
		*/
			insert into #pid 
			select id, uid, name
			from sysobjects 
			where type in ("S", "U")
		end
		else
		begin
			insert into #pid
			select id, uid, name
			from sysobjects
			where  uid = user_id(@pktable_owner)
			and type in ("S", "U")
		end
	end
		
	if @fktable_name is not null
	begin 
		if (@fktable_owner is null)
		begin
			/* 
			** owner is NULL, so default to the current user
			** who owns this table, otherwise default to dbo
			** who owns this table.
			*/
			insert into #fid 
			select id, uid, name
			from sysobjects 
			where name = @fktable_name and uid = user_id()
			and type in ("S", "U")

			/* 
			** If the current user does not own the table, see
			** if the DBO of the current database owns the table.
			*/

			if ((select count(*) from #pid ) = 0)
			begin
				insert into #fid 
				select id, uid, name
				from sysobjects 
				where name = @fktable_name and uid = 1
				and type in ("S", "U")
			end
		end
		else
		begin
			insert into #fid
			select id, uid, name
			from sysobjects
			where name = @fktable_name 
			and uid = user_id(@fktable_owner)
			and type in ("S", "U")
		end
	end
	else
	begin
		if (@fktable_owner is null)
		begin
		/* 
		** If neither fktable_name nor fktable_owner is specified,
		** then we are interested in every user table or systme 
		** table.
		*/			
			insert into #fid 
			select id, uid, name
			from sysobjects 
			where type in ("S", "U")
		end
		else
		begin
			insert into #fid
			select id, uid, name
			from sysobjects
			where  uid = user_id(@fktable_owner)
			and type in ("S", "U")
		end
	end

	if (((select count(*) from #fid ) = 0) or
		((select count(*) from #pid) = 0))
	begin
		/* 17461, "Object does not exist in this database." */
		exec sp_getmessage 17461, @msg output
		print @msg
		return (1)
	end

	create table #fkey_res( pktable_qualifier varchar(32),
				pktable_owner       varchar(32),
				pktable_name       varchar(32),
				pkcolumn_name      varchar(32),
				fktable_qualifier varchar(32),
				fktable_owner       varchar(32),
				fktable_name       varchar(32),
				fkcolumn_name       varchar(32),
				key_seq           smallint,	
				update_rule smallint, 
				delete_rule smallint)
	create table #pkeys(seq int,  keys varchar(30) null)
	create table #fkeys(seq int, keys varchar(30) null)

	/*
	** Since there are possibly multiple rows in sysreferences
	** that describe foreign and primary key relationships among
	** two tables, so we declare a cursor on the selection from
	** sysreferences and process the output at row by row basis.
	*/
		
	declare curs_sysreferences cursor
	for
	select tableid, reftabid, keycnt,
	fokey1, fokey2, fokey3, fokey4, fokey5, fokey6, fokey7, fokey8, 
	fokey9, fokey10, fokey11, fokey12, fokey13, fokey14, fokey15,
	fokey16, refkey1, refkey2, refkey3, refkey4, refkey5,
	refkey6, refkey7, refkey8, refkey9, refkey10, refkey11,
	refkey12, refkey13, refkey14, refkey15, refkey16
	from sysreferences
	where tableid in (
		select fid from #fid)
	and reftabid in (
		select pid from #pid)
	and frgndbname is NULL and pmrydbname is NULL
	for read only

	open  curs_sysreferences

	fetch  curs_sysreferences into @ftabid, @ptabid, @keycnt,@fokey1, 
	@fokey2, @fokey3,  @fokey4, @fokey5, @fokey6, @fokey7, @fokey8, 
	@fokey9, @fokey10, @fokey11, @fokey12, @fokey13, @fokey14, @fokey15, 
	@fokey16, @refkey1, @refkey2, @refkey3, @refkey4, @refkey5, @refkey6, 
	@refkey7, @refkey8, @refkey9, @refkey10, @refkey11, @refkey12, 
	@refkey13, @refkey14, @refkey15, @refkey16

	while (@@sqlstatus = 0)
	begin
		/*
		** For each row of sysreferences which describes a foreign-
		** primary key relationship, do the following.
		*/

		/*
		** First store the column names that belong to primary keys
		** in table #pkeys for later retrieval.
		*/

		delete #pkeys
		insert #pkeys values(1, col_name(@ptabid,@refkey1))
		insert #pkeys values(2, col_name(@ptabid,@refkey2))
		insert #pkeys values(3, col_name(@ptabid,@refkey3))
		insert #pkeys values(4, col_name(@ptabid,@refkey4))
		insert #pkeys values(5, col_name(@ptabid,@refkey5))
		insert #pkeys values(6, col_name(@ptabid,@refkey6))
		insert #pkeys values(7, col_name(@ptabid,@refkey7))
		insert #pkeys values(8, col_name(@ptabid,@refkey8))
		insert #pkeys values(9, col_name(@ptabid,@refkey9))
		insert #pkeys values(10, col_name(@ptabid,@refkey10))
		insert #pkeys values(11, col_name(@ptabid,@refkey11))
		insert #pkeys values(12, col_name(@ptabid,@refkey12))
		insert #pkeys values(13, col_name(@ptabid,@refkey13))
		insert #pkeys values(14, col_name(@ptabid,@refkey14))
		insert #pkeys values(15, col_name(@ptabid,@refkey15))
		insert #pkeys values(16, col_name(@ptabid,@refkey16))
	
		/*
		** Second store the column names that belong to foreign keys
		** in table #fkeys for later retrieval.
		*/
		
		delete #fkeys
		insert #fkeys values(1, col_name(@ftabid,@fokey1))
		insert #fkeys values(2, col_name(@ftabid,@fokey2))
		insert #fkeys values(3, col_name(@ftabid,@fokey3))
		insert #fkeys values(4, col_name(@ftabid,@fokey4))
		insert #fkeys values(5, col_name(@ftabid,@fokey5))
		insert #fkeys values(6, col_name(@ftabid,@fokey6))
		insert #fkeys values(7, col_name(@ftabid,@fokey7))
		insert #fkeys values(8, col_name(@ftabid,@fokey8))
		insert #fkeys values(9, col_name(@ftabid,@fokey9))
		insert #fkeys values(10, col_name(@ftabid,@fokey10))
		insert #fkeys values(11, col_name(@ftabid,@fokey11))
		insert #fkeys values(12, col_name(@ftabid,@fokey12))
		insert #fkeys values(13, col_name(@ftabid,@fokey13))
		insert #fkeys values(14, col_name(@ftabid,@fokey14))
		insert #fkeys values(15, col_name(@ftabid,@fokey15))
		insert #fkeys values(16, col_name(@ftabid,@fokey16))
	
		/* 
		** For each column of the current foreign-primary key relation,
		** create a row into result table: #fkey_res.
		*/

		select @i = 1
		while (@i <= @keycnt)
		begin
			insert into #fkey_res 
				select @pktable_qualifier,
				(select user_name(uid) from #pid where pid = @ptabid),
				object_name(@ptabid),
				(select keys from #pkeys where seq = @i),
				@fktable_qualifier,
				(select user_name(uid) from #fid where fid = @ftabid),
				object_name(@ftabid), 
				(select keys from #fkeys where seq = @i),@i,
				1, 1
			select @i = @i + 1
		end
		
		/* 
		** Go to the next foreign-primary key relationship if any.
		*/

		fetch  curs_sysreferences into @ftabid, @ptabid, @keycnt,@fokey1, 
		@fokey2, @fokey3,  @fokey4, @fokey5, @fokey6, @fokey7, @fokey8, 
		@fokey9, @fokey10, @fokey11, @fokey12, @fokey13, @fokey14, @fokey15, 
		@fokey16, @refkey1, @refkey2, @refkey3, @refkey4, @refkey5, @refkey6, 
		@refkey7, @refkey8, @refkey9, @refkey10, @refkey11, @refkey12, 
		@refkey13, @refkey14, @refkey15, @refkey16
	end

	close curs_sysreferences
	deallocate cursor curs_sysreferences

	/*
	** Everything is now in the result table #fkey_res, so go ahead
	** and select from the table now.
	*/
		
	select pktable_qualifier, pktable_owner, pktable_name,pkcolumn_name,
	fktable_qualifier, fktable_owner, fktable_name, fkcolumn_name,
	key_seq, update_rule, delete_rule
	from #fkey_res
	order by fktable_name,fktable_owner,key_seq, fktable_qualifier
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_foreignkey')
begin
	drop procedure sp_foreignkey
end
go
print "Installing sp_foreignkey"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */

/*
** Messages for "sp_foreignkey"         17560
**
** 17390, "Table or view name must be in 'current' database."
** 17560, "Foreign key table doesn't exist."
** 17561, "Primary key table doesn't exist."
** 17562, "Only the owner of the table may define a foreign key."
** 17563, "The table does not have a column named '%1!'."
** 	  ** substitute in "@col[1-8]" for the arg.
** 17564, "Primary key does not exist with the same number of columns as the foreign key."
** 17565, "Primary key does not exist."
** 17566, "Datatypes of the column '%1!' in the keys are different." 
** 	  ** substitute in "@col[1-8]" for the arg.
** 17567, "New foreign key added."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_foreignkey 
@tabname  varchar(92),		/* name of table that we are doing */
@pktabname varchar(92),		/* name of table with primary key */
@col1     varchar(30), 		/* column name of table we are doing */
@col2     varchar(30) = NULL,
@col3     varchar(30) = NULL,
@col4     varchar(30) = NULL,
@col5     varchar(30) = NULL,
@col6     varchar(30) = NULL,
@col7     varchar(30) = NULL,
@col8     varchar(30) = NULL
as

declare @uid smallint		/* id of owner of the talbe */
declare @cnt    int		/* how many columns are in foreign key */

declare @pkey1 int		/* colids of the foreign key */
declare @pkey2 int
declare @pkey3 int
declare @pkey4 int
declare @pkey5 int
declare @pkey6 int
declare @pkey7 int
declare @pkey8 int

declare @fkey1 int		/* colids of the primary key */
declare @fkey2 int
declare @fkey3 int
declare @fkey4 int
declare @fkey5 int
declare @fkey6 int
declare @fkey7 int
declare @fkey8 int

declare @msg   varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see that the tabname is local.
*/
if @tabname like "%.%.%"
begin
	if substring(@tabname, 1, charindex(".", @tabname) - 1) != db_name()
	begin
		/*
		** 17390, "Table or view name must be in 'current' database."
		*/
		exec sp_getmessage 17390, @msg output
		print @msg
		return (1)
	end
end
if @pktabname like "%.%.%"
begin
	if substring(@pktabname, 1, charindex(".", @pktabname) - 1) != db_name()
	begin
		/*
		** 17390, "Table or view name must be in 'current' database."
		*/
		exec sp_getmessage 17390, @msg output
		print @msg
		return (1)
	end
end

/*
**  See if we can find the objects.  They must be a system table, user table,
**  or view.  The low 3 bits of sysobjects.sysstat indicate what the 
**  object type is -- it's more reliable than using sysobjects.type which
**  could change.
*/
if not exists (select *
	from sysobjects
		where id = object_id(@tabname)
			and (sysstat & 7 = 1		/* system table */
				or sysstat & 7 = 2	/* view */
				or sysstat & 7 = 3))	/* user table */
/*
**  If either of the tables don't exist, quit.
*/
begin
    /*
    ** 17560, "Foreign key table doesn't exist."
    */
    exec sp_getmessage 17560, @msg output
    print @msg
    return (1)
end 
if not exists (select *
	from sysobjects
		where id = object_id(@pktabname)
			and (sysstat & 7 = 1
				or sysstat & 7 = 2
				or sysstat & 7 = 3))
begin
    /*
    ** 17561, "Primary key table doesn't exist."
    */
    exec sp_getmessage 17561, @msg output
    print @msg
    return (1)
end 

/*
**  Only the owner of the table can define it's foreign keys.
*/
select @uid = uid
	from sysobjects
		where id = object_id(@tabname)
			and (sysstat & 7 = 1            /* system table */
				or sysstat & 7 = 2      /* view */
				or sysstat & 7 = 3)     /* user table */

if @uid != user_id()
begin
	/*
        ** 17562, "Only the owner of the table may define a foreign key."
	*/
	exec sp_getmessage 17562, @msg output
	print @msg
	return (1)
end

/*
**  Now check to see that the foreign key columns exist.
*/
select @cnt = 1, @fkey1 = colid
	from syscolumns
		where name = @col1 
			and id = object_id(@tabname)
if @fkey1 is NULL
begin
	/*
	** 17563, "The table does not have a column named '%1!'."
	*/
	exec sp_getmessage 17563, @msg output
	print @msg, @col1 
	return (1)
end

if @col2 is not NULL
begin
	select @cnt = @cnt + 1, @fkey2 = colid
		from syscolumns
			where name = @col2 
				and id = object_id(@tabname)
	if @fkey2 is NULL
	begin
		/*
		** 17563, "The table does not have a column named '%1!'."
		*/
		exec sp_getmessage 17563, @msg output
		print @msg, @col2
		return (1)
	end
end
else goto foreign_ok

if @col3 is not NULL
begin
	select @cnt = @cnt + 1, @fkey3 = colid
		from syscolumns
			where name = @col3 
				and id = object_id(@tabname)
	if @fkey3 is NULL
	begin
		/*
		** 17563, "The table does not have a column named '%1!'."
		*/
		exec sp_getmessage 17563, @msg output
		print @msg, @col3
		return (1)
	end
end
else goto foreign_ok

if @col4 is not NULL
begin
	select @cnt = @cnt + 1, @fkey4 = colid
		from syscolumns
			where name = @col4 
				and id = object_id(@tabname)
	if @fkey4 is NULL
	begin
		/*
		** 17563, "The table does not have a column named '%1!'."
		*/
		exec sp_getmessage 17563, @msg output
		print @msg, @col4
		return (1)
	end
end
else goto foreign_ok

if @col5 is not NULL
begin
	select @cnt = @cnt + 1, @fkey5 = colid
		from syscolumns
			where name = @col5 
				and id = object_id(@tabname)
	if @fkey5 is NULL
	begin
		/*
		** 17563, "The table does not have a column named '%1!'."
		*/
		exec sp_getmessage 17563, @msg output
		print @msg, @col5
		return (1)
	end
end
else goto foreign_ok

if @col6 is not NULL
begin
	select @cnt = @cnt + 1, @fkey6 = colid
		from syscolumns
			where name = @col6 
				and id = object_id(@tabname)
	if @fkey6 is NULL
	begin
		/*
		** 17563, "The table does not have a column named '%1!'."
		*/
		exec sp_getmessage 17563, @msg output
		print @msg, @col6
		return (1)
	end
end
else goto foreign_ok

if @col7 is not NULL
begin
	select @cnt = @cnt + 1, @fkey7 = colid
		from syscolumns
			where name = @col7 
				and id = object_id(@tabname)
	if @fkey7 is NULL
	begin
		/*
		** 17563, "The table does not have a column named '%1!'."
		*/
		exec sp_getmessage 17563, @msg output
		print @msg, @col7
		return (1)
	end
end
else goto foreign_ok

if @col8 is not NULL
begin
	select @cnt = @cnt + 1, @fkey8 = colid
		from syscolumns
			where name = @col8 
				and id = object_id(@tabname)
	if @fkey8 is NULL
	begin
		/*
		** 17563, "The table does not have a column named '%1!'."
		*/
		exec sp_getmessage 17563, @msg output
		print @msg, @col8
		return (1)
	end
end


/*
**  If we made it this far then all the columns for the foreign key are ok.
*/
foreign_ok:

/*
**  Now let's check out the primary key that the foreign key is on.
**  There must be the same number of columns in the key and the
**  base types of the columns must agree.
*/
select @pkey1 = key1, @pkey2 = key2, @pkey3 = key3, @pkey4 = key4,
	@pkey5 = key5, @pkey6 = key6, @pkey7 = key7, @pkey8 = key8
		from syskeys
	where id = object_id(@pktabname)
		and type = 1
		and keycnt = @cnt

/*
**  If @pkey1 is null then there is no such primary key or the number of
**  columns in the primary key are not the same as the number of columns
**  in the foreign key.
*/
if @pkey1 is  NULL
begin
	if exists (select *
			from syskeys
		where id = object_id(@pktabname)
			and type = 1)
	begin
		/*
		** 17564, "Primary key does not exist with the same number of columns as the foreign key."
		*/
		exec sp_getmessage 17564, @msg output
	        print @msg
	end
	else
	begin
		/*
		** 17565, "Primary key does not exist."
		*/
		exec sp_getmessage 17565, @msg output
		print @msg
	end
	return (1)
end

/*
**  Since we have the right number of columns in the foreign and primary keys,
**  check that there base datatypes agree.
*/
if not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey1
			and a.id = object_id(@tabname)
			and b.colid = @pkey1
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col1
	return (1)
end

if @fkey2 is not NULL and not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey2
			and a.id = object_id(@tabname)
			and b.colid = @pkey2
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col2
	return (1)
end
else goto doinsert

if @fkey3 is not NULL and not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey3
			and a.id = object_id(@tabname)
			and b.colid = @pkey3
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col3
	return (1)
end
else goto doinsert

if @fkey4 is not NULL and not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey4
			and a.id = object_id(@tabname)
			and b.colid = @pkey4
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col4
	return (1)
end

if @fkey5 is not NULL and not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey5
			and a.id = object_id(@tabname)
			and b.colid = @pkey5
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col5
	return (1)
end
else goto doinsert

if @fkey6 is not NULL and not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey6
			and a.id = object_id(@tabname)
			and b.colid = @pkey6
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col6
	return (1)
end
else goto doinsert

if @fkey7 is not NULL and not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey7
			and a.id = object_id(@tabname)
			and b.colid = @pkey7
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col7
	return (1)
end
else goto doinsert

if @fkey8 is not NULL and not exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.colid = @fkey8
			and a.id = object_id(@tabname)
			and b.colid = @pkey8
			and b.id = object_id(@pktabname)
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	/*
	** 17566, "Datatypes of the column '%1!' in the keys are different."
	*/
	exec sp_getmessage 17566, @msg output
	print @msg, @col8
	return (1)
end

/*
**  Everything is consistent so add the foreign key to syskeys.
*/
doinsert:

insert syskeys (id, type, depid, keycnt, size, key1, key2, key3, key4, key5,
	key6, key7, key8, depkey1, depkey2, depkey3, depkey4, depkey5,
	depkey6, depkey7, depkey8)
values (object_id(@tabname), 2, object_id(@pktabname), @cnt, 0, @fkey1, 
	@fkey2, @fkey3, @fkey4, @fkey5,
	@fkey6, @fkey7, @fkey8, @pkey1, @pkey2, @pkey3, @pkey4, @pkey5,
	@pkey6, @pkey7, @pkey8)   

/* 
** 17567, "New foreign key added."
*/
exec sp_getmessage 17567, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_foreignkey', 'anymode'
go
grant execute on sp_foreignkey to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpconstraint')
begin
	drop procedure sp_helpconstraint
end
go
print "Installing sp_helpconstraint"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*
** 17460, "Object must be in the current database."
** 17461, "Object does not exist in this database."
** 18024, "Object does not have any declarative constraints."
*/

/*
** Type of declarative constraints returned by this routine are as follows :
**	DEFAULT		     - report the defaults on a column
**	PRIMARY KEY	     - implies clustered index
**	UNIQUE  KEY	     - implies non-clustered index; if no clustered
**			       index exists, this will be clustered
**	CHECK CONSTRAINT     - check constraint, either column or table
**	REFERENCE CONSTRAINT - foreign key/ referential constraint
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/
CREATE PROCEDURE sp_helpconstraint
@objname varchar(92),		/* table to report constraints on */
@propt   varchar(10) = "terse"	/* print option :
				** "detail" - full print
				** not supplied or otherwise - terse print
				*/
AS

DECLARE @indid int			/* the index id of an index */
DECLARE @keys varchar(200)		/* string to build up index key in */
DECLARE @inddesc varchar(68)		/* string to build up index desc in */
DECLARE @clust int, @nonclust int	/* flag if clust/non-clust index*/
DECLARE @msg varchar(90)
DECLARE @colcnt int
DECLARE @indstat   int			/* status of sysindexes  */
DECLARE @indstat2  int			/* status2 of sysindexes */
DECLARE @pmytabid  int			/* flag/id of referencing table */
DECLARE @cnstrname varchar(30)
DECLARE @foreign_keys varchar(125)
DECLARE @refrncd_keys varchar(125)
DECLARE @frgntab varchar(30), @pmrytab varchar(30)

/* Declarations for sysreferences table cursor fetch */
DECLARE @indexid int, @constrid int, @tableid int, @reftabid int, @keycnt int
DECLARE @fokey1 int,  @fokey2 int,  @fokey3 int,  @fokey4 int,  @fokey5  int
DECLARE @fokey6 int,  @fokey7 int,  @fokey8 int,  @fokey9 int,  @fokey10 int
DECLARE @fokey11 int, @fokey12 int, @fokey13 int, @fokey14 int, @fokey15 int
DECLARE @refkey1 int, @refkey2 int, @refkey3 int, @refkey4 int, @refkey5  int
DECLARE @refkey6 int, @refkey7 int, @refkey8 int, @refkey9 int, @refkey10 int
DECLARE @refkey11 int, @refkey12 int, @refkey13 int, @refkey14 int
DECLARE @refkey15 int, @refkey16 int, @fokey16 int, @status int
DECLARE @frgndbid int, @pmrydbid int
DECLARE @frgndbname varchar(30), @pmrydbname varchar(30)

IF @@trancount = 0
BEGIN
	SET chained off
END

SET transaction isolation level 1

/*
**  Check to see that the object names are local to the current database.
*/
if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
BEGIN
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return (1)
END

/*
**  Check to see the the table exists and in the same scan, find if
**  the table has any check constraints/foreign-key constraints, or
**  is being referenced by other tables.
*/
SELECT  @colcnt = 0
SELECT  @colcnt = id,			/* Flag for row in sysobjects found */
	@clust    = (sysstat  & 16),	/* Flag for clustered index */
        @nonclust = (sysstat  & 32),	/* Flag for non-clustered index */
        @constrid = ckfirst,		/* Flag for table check constraint */
	@keycnt   = (sysstat2 & 4),	/* Flag for > 1 table check constr */
	@pmytabid = (sysstat2 & 2),	/* Flag for foreign key constraint */
	@reftabid = (sysstat2 & 1)	/* Flag for referenced table constr*/
FROM sysobjects
WHERE id = object_id(@objname)

/*
**  If table doesn't exist, return.
*/
IF (@colcnt = 0)
BEGIN
	/* 17461, "Object does not exist in this database." */
	exec sp_getmessage 17461, @msg out
	print @msg
	return (1)
END

/*    Get number of columns in this table. */
SELECT @colcnt = count(*)
FROM syscolumns
WHERE id = object_id(@objname)

/*    Check if no columns have any constraints or default */
IF (@colcnt = (SELECT count(*)
	       FROM syscolumns
	       WHERE id = object_id(@objname)
		   AND domain = 0	/* No column check constraint */
		   AND cdefault = 0))	/* No defaults */
BEGIN
	SELECT @colcnt = 0
END

/*
**  If no constraints on this table, return.
*/
IF (@clust = 0			/* No clustered index */
    AND @nonclust = 0		/* No non-clustered index */
    AND @constrid = 0		/* No table check constraints */
    AND @pmytabid = 0		/* No foreign key constraints */
    AND @reftabid = 0		/* No references to this table */
    AND @colcnt   = 0)		/* No column default or check constraints */
BEGIN
	/* 18024, "Object does not have any constraints." */
	EXEC sp_getmessage 18024, @msg out
	PRINT @msg
	RETURN (1)
END

/*
** Template for the table we will output.
**	    id   : this may not be useful?
**	    ermsg: message number assigned by user for this constraint
**	    name : this will contain name as given by user or system
**	    colno: number of columns involved in constraint
**	    type : one of (reference constraint, check constraint)
**	    msg  : one of (user defined, system standard)
**	    text : actual text of this constraint	    
** save the info in a temporary table that we'll print out at the end.
*/
CREATE TABLE #spconstrtab (
       constraint_id	int,
       constraint_name	varchar(30),
       constraint_colno int,
       constraint_ermsg int,
       constraint_type	varchar(25),
       constraint_msg	varchar(255) null,
       constraint_desc	varchar(255) null)

/*
**  Check if the object has any defaults
*/
IF (@colcnt > 0)
BEGIN
INSERT INTO #spconstrtab
       SELECT	o.id, o.name, 1, 0,
		"default value",
		NULL,
		m.text
       FROM syscolumns c, sysobjects o, syscomments m
       WHERE c.id = object_id(@objname)
	     AND c.cdefault = o.id
	     AND o.id = m.id
END

/*
**  See if the object has any check constraints
**  There may be more than one entry in sysconstraints for the object.
**  Note :  We only handle 1 line of text, need to improve for more lines.
*/
IF (@colcnt > 0 OR @constrid > 0)
BEGIN
INSERT INTO #spconstrtab
       SELECT	o.id, o.name, 1, c.error,
		"check constraint",
		"standard system error message number : 548",
		m.text
       FROM sysconstraints c, sysobjects o, syscomments m
       WHERE c.tableid = object_id(@objname)
	     AND c.constrid = o.id
	     AND o.id = m.id
	     AND (o.sysstat & 15 = 7)
END

/*
**  Now we search for UNIQUE and PRIMARY KEY (only declarative) constraints
*/
DECLARE curs_sysindexes
CURSOR FOR
	SELECT keycnt, indid, status, status2
	FROM   sysindexes
	WHERE  id = object_id(@objname)
	       AND indid > 0
	       AND status2 & 2 = 2
FOR READ ONLY

OPEN curs_sysindexes

FETCH curs_sysindexes
INTO  @keycnt, @indexid, @indstat, @indstat2

WHILE (@@sqlstatus = 0)
BEGIN
	/*
	**  First we'll figure out what the keys are.
	*/
	DECLARE @i int
	DECLARE @thiskey varchar(30)

	SELECT @keys = "", @i = 1

	SET NOCOUNT ON

	WHILE @i <= @keycnt
	BEGIN
		SELECT @thiskey = index_col(@objname, @indexid, @i)

		IF @thiskey IS NULL
		BEGIN
			GOTO keysdone
		END

		IF @i > 1
		BEGIN
			SELECT @keys = @keys + ", "
		END
			
		SELECT @keys = @keys + index_col(@objname, @indexid, @i)

		/*
		**  Increment @i so it will check for the next key.
		*/
		SELECT @i = @i + 1

	END

	/*
	**  When we get here we now have all the keys.
	*/
	keysdone:
		SET NOCOUNT OFF

	/*
	** Check if we have a PRIMARY KEY constraint or a UNIQUE constraint
	** Note that we are only dealing with declarative indexes
	*/
	IF (@indstat & 2048 = 2048)
	BEGIN
		SELECT @inddesc = "PRIMARY KEY "
	END
	ELSE
	BEGIN
		SELECT @inddesc = "UNIQUE "
	END

	/*
	**  Get the keys involved in the declarative constraint
	*/
	SELECT @inddesc = @inddesc + "INDEX (" + @keys + ")"

	/*
	**  clustered or nonclustered index
	**  Note that the system by default creates an index
	*/
	IF @indexid = 1
	BEGIN
		SELECT @inddesc = @inddesc + " : CLUSTERED"
	END
	IF @indexid > 1
	BEGIN
		SELECT @inddesc = @inddesc + " : NONCLUSTERED"
	END

	/*
	**  Display if this key is referenced by other table
	*/
	IF (@indstat2 & 1 = 1)
	BEGIN
		SELECT @inddesc = @inddesc + ", FOREIGN REFERENCE"
	END

	/*
	**  Now we have the whole description for the index so we'll
	**  add the goods to the temporary table.
	*/
	INSERT INTO #spconstrtab
	       SELECT indid, name, @i - 1, 0,
		      "unique constraint",
		      "standard system error message number : 2601",
		      @inddesc
	       FROM sysindexes i
	       WHERE id = object_id(@objname)
		   AND indid = @indexid

FETCH curs_sysindexes
INTO  @keycnt, @indexid, @indstat, @indstat2

END

CLOSE curs_sysindexes

/*
** Now we obtain the referential dependency information
** The search for matching tableid or reftabid applies to objects in
** this database only (null frgndbname/pmrydbname tells us).
*/
DECLARE curs_sysreferences
CURSOR FOR
       SELECT constrid, tableid, reftabid, keycnt, status, frgndbid, pmrydbid,
       	      fokey1, fokey2, fokey3, fokey4, fokey5, fokey6,
	      fokey7, fokey8, fokey9, fokey10, fokey11, fokey12,
	      fokey13, fokey14, fokey15, fokey16,
	      refkey1, refkey2, refkey3, refkey4, refkey5, refkey6,
	      refkey7, refkey8, refkey9, refkey10, refkey11, refkey12,
	      refkey13, refkey14, refkey15, refkey16,
	      frgndbname, pmrydbname
       FROM   sysreferences
       WHERE  (tableid  = object_id(@objname)
               AND (frgndbname = NULL
                    OR db_id(frgndbname) = db_id()))
          OR  (reftabid = object_id(@objname)
               AND (pmrydbname = NULL
                    OR db_id(pmrydbname) = db_id()))
FOR READ ONLY

OPEN curs_sysreferences

FETCH curs_sysreferences
INTO @constrid, @tableid, @reftabid, @keycnt, @status, @frgndbid, @pmrydbid,
     @fokey1, @fokey2, @fokey3, @fokey4, @fokey5, @fokey6,
     @fokey7, @fokey8, @fokey9, @fokey10, @fokey11, @fokey12,
     @fokey13, @fokey14, @fokey15, @fokey16,
     @refkey1, @refkey2, @refkey3, @refkey4, @refkey5, @refkey6,
     @refkey7, @refkey8, @refkey9, @refkey10, @refkey11, @refkey12,
     @refkey13, @refkey14, @refkey15, @refkey16,
     @frgndbname, @pmrydbname

WHILE (@@sqlstatus = 0)
BEGIN

/*
** Set the Database id's from the Database names
*/
SELECT @pmrydbid = db_id()
SELECT @frgndbid = db_id()
IF @frgndbname != NULL
	SELECT @frgndbid = db_id(@frgndbname)
IF @pmrydbname != NULL
	SELECT @pmrydbid = db_id(@pmrydbname)

/*
**   Check if either primary or dependent dbids are from this database.
**   If both are not, that means we have an invalid entry here.
**   Otherwise prefix the database name to the tablename.
**   Only look up table names if dbid is non-null (i.e., database exists),
**   otherwise object_name will default to current database.
*/
SELECT  @pmrytab = "*"
SELECT  @frgntab = "*"
IF @pmrydbid != NULL
	SELECT  @pmrytab = object_name(@reftabid, @pmrydbid)
IF @frgndbid != NULL
	SELECT	@frgntab = object_name(@tableid,  @frgndbid)

/*
** Need to enhance this ...
*/
IF @frgndbid != db_id()
BEGIN
	SELECT @frgntab = @frgndbname + ".." + @frgntab	
END
ELSE
BEGIN
	IF @pmrydbid != db_id()
		SELECT @pmrytab = @pmrydbname + ".." + @pmrytab	
END

SELECT @foreign_keys = convert(char(255),
	  isnull(col_name(@tableid, @fokey1 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey2 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey3 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey4 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey5 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey6 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey7 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey8 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey9 , @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey10, @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey11, @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey12, @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey13, @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey14, @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey15, @frgndbid), "*") + ", "
	+ isnull(col_name(@tableid, @fokey16, @frgndbid), "*"))

SELECT  @refrncd_keys = convert(char(255),
	  isnull(col_name(@reftabid, @refkey1 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey2 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey3 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey4 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey5 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey6 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey7 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey8 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey9 , @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey10, @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey11, @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey12, @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey13, @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey14, @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey15, @pmrydbid), "*") + ", "
	+ isnull(col_name(@reftabid, @refkey16, @pmrydbid), "*"))

/* trim the list of key-columns */
SELECT @foreign_keys =
       	    substring(@foreign_keys, 1, patindex("%, *%", @foreign_keys) - 1)
SELECT @refrncd_keys =
	    substring(@refrncd_keys, 1, patindex("%, *%", @refrncd_keys) - 1)

SELECT @cnstrname = isnull(object_name(@constrid, @frgndbid), "*")

IF db_id() = @frgndbid
BEGIN
       INSERT INTO #spconstrtab
	      SELECT  @constrid, @cnstrname, @keycnt, c.error,
		      "referential constraint",
		      "standard system error message number : 547",
		      @frgntab + " FOREIGN KEY (" + @foreign_keys +
		      ") REFERENCES " + @pmrytab + "(" + @refrncd_keys + ")"
	      FROM sysconstraints c
	      WHERE c.constrid = @constrid
END
ELSE
BEGIN
       INSERT INTO #spconstrtab
	      SELECT  @constrid, @cnstrname, @keycnt, 0,
		      "referential constraint",
		      "standard system error message number : 547",
		      @frgntab + " FOREIGN KEY (" + @foreign_keys +
		      ") REFERENCES " + @pmrytab + "(" + @refrncd_keys + ")"
END

FETCH curs_sysreferences
INTO @constrid, @tableid, @reftabid, @keycnt, @status, @frgndbid, @pmrydbid,
     @fokey1, @fokey2, @fokey3, @fokey4, @fokey5, @fokey6,
     @fokey7, @fokey8, @fokey9, @fokey10, @fokey11, @fokey12,
     @fokey13, @fokey14, @fokey15, @fokey16,
     @refkey1, @refkey2, @refkey3, @refkey4, @refkey5, @refkey6,
     @refkey7, @refkey8, @refkey9, @refkey10, @refkey11, @refkey12,
     @refkey13, @refkey14, @refkey15, @refkey16,
     @frgndbname, @pmrydbname

END

CLOSE curs_sysreferences

/*
**	Now we setup the error message, if user defined.
*/
UPDATE #spconstrtab
SET constraint_msg = description 
FROM sysusermessages u, #spconstrtab c
WHERE c.constraint_ermsg > 20000
      AND u.error = c.constraint_ermsg

/*
**	Now prettyprint the results
*/
IF @propt NOT LIKE "detail%"
BEGIN
	DECLARE @len1 int, @len2 int, @len3 int

	SELECT @len1 = max(datalength(constraint_name)) FROM #spconstrtab
	SELECT @len2 = max(datalength(constraint_desc)) FROM #spconstrtab

	IF (@len1 < 15 and @len2 < 60)
	BEGIN
		SELECT
			name = convert(char(15), constraint_name),
			definition = convert(char(60), constraint_desc)	
		FROM #spconstrtab
		ORDER BY constraint_type
	END
	ELSE IF (@len2 < 60)
	BEGIN
		SELECT
			name = constraint_name,
			definition = convert(char(60), constraint_desc)	
		FROM #spconstrtab
		ORDER BY constraint_type
	END
	ELSE
	BEGIN
		SELECT
			name = constraint_name,
			definition = constraint_desc	
		FROM #spconstrtab
		ORDER BY constraint_type
	END
END
/* Show all details - pretty printing is not required for this perhaps ? */
ELSE
BEGIN
	SELECT @len1 = max(datalength(constraint_name)) FROM #spconstrtab
	SELECT @len2 = max(datalength(constraint_msg )) FROM #spconstrtab
	SELECT @len3 = max(datalength(constraint_desc)) FROM #spconstrtab

	IF (@len1 < 15 and @len3 < 60)
	BEGIN
		SELECT	name = convert(char(15), constraint_name),
			definition = convert(char(60), constraint_desc),
			msg  = constraint_msg
		FROM #spconstrtab
		ORDER BY constraint_type
	END
	ELSE
	BEGIN
		SELECT	name = constraint_name,
			type = constraint_type,
			definition = constraint_desc,	
			msg  = constraint_msg
		FROM #spconstrtab
		ORDER BY constraint_type
	END
END

RETURN (0)
go
exec sp_procxmode 'sp_helpconstraint', 'anymode'
go
grant execute on sp_helpconstraint to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpdb')
begin
	drop procedure sp_helpdb
end
go
print "Installing sp_helpdb"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helpdb"             17590
**
** 17590, "The specified database does not exist."
** 17591, "no options set"
** 17592, " -- unused by any segments --"
*/
create procedure sp_helpdb
@dbname varchar(30) = NULL			/* database name to change */
as

declare @showdev	int
declare @allopts	int
declare @all2opts	int
declare @thisopt	int
declare @optmask	int
declare @pagekb		int
declare @msg 		varchar(90)
declare @sptlang	int
declare @len1 int, @len2 int, @len3 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @sptlang = @@langid

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17050 and 17069
		and langid = @@langid)
	    select @sptlang = 0
	else
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17110 and 17119
		and langid = @@langid)
	    select @sptlang = 0
end

set nocount on


/*
**  If no database name given, get 'em all.  Otherwise, count how many
**  databases match the specified name.
*/
if @dbname is null
	select @dbname = "%",
	       @showdev = count(*) from master.dbo.sysdatabases
else
	select @showdev = count(*)
			   from master.dbo.sysdatabases
			   where name like @dbname

/*
**  Sure the database exists
*/
if @showdev = 0
begin
	/* 17590, "The specified database does not exist." */
	exec sp_getmessage 17590, @msg out
	print @msg
	return (1)
end

/*
**  Set allopts to be the sum of all possible user-settable database status
**  bits.  (Note that there are 2 groups of such bits.)  If we can't get
**  the option mask from spt_values, guess at the correct value.
*/
select @allopts = number
from master.dbo.spt_values
where	type = "D"
  and	name = "ALL SETTABLE OPTIONS"
if (@allopts is NULL)
	select @allopts = 4 | 8 | 16 | 512 | 1024 | 2048 | 4096 | 8192

select @all2opts = number
from master.dbo.spt_values
where	type = "D2"
  and	name = "ALL SETTABLE OPTIONS"
if (@all2opts is NULL)
	select @all2opts = 1 | 2 | 4

/*
** @allopts (sysdatabases.status options) should also contain some
** NON-settable options that we want to check for:
**	 32 = "don't recover"
**	256 = "not recovered"
*/
select @allopts = @allopts | 32 | 256

/*
** @all2opts (sysdatabases.status2 options) should also contain a
** NON-settable option that we want to check for:
**	 16 = "offline"
*/
select @all2opts = @all2opts | 16

/*
**  Since we examine the status bits in sysdatabase and turn them
**  into english, we need a temporary table to build the descriptions.
*/
create table #spdbdesc
(
	dbid	smallint null,
	dbdesc	varchar(102) null
)


/*
**  Initialize #spdbdesc from sysdatabases
*/
insert into #spdbdesc (dbid)
		select dbid 
			from master.dbo.sysdatabases
				where name like @dbname
/*
**  Now for each dbid in #spdbdesc, build the database status
**  description.
*/
declare @curdbid smallint		/* the one we're currently working on */
declare @dbdesc varchar(102)		/* the total description for the db */
declare @bitdesc varchar(30)		/* the bit description for the db */

/*
**  Set @curdbid to the first dbid.
*/
select @curdbid = min(dbid)
	from #spdbdesc
while @curdbid is not NULL
begin
	/*
	**  Initialize @dbdesc.
	*/
	select @dbdesc = ""

	/*
	**  Check status options (spt_values.type = "D")
	*/
	select @thisopt = 1
	select @optmask = @allopts	/* status options */
	while (@optmask != 0)		/* until all set options noted ... */
	begin
		/*
		** If this option is user-settable, check for it
		*/
		if (@optmask & @thisopt = @thisopt)
		begin
			select @bitdesc = null

			select @bitdesc = m.description
			from master.dbo.spt_values v,
			     master.dbo.sysdatabases d,
			     master.dbo.sysmessages m
			where d.dbid = @curdbid
				and v.type = "D"
				and d.status & v.number = @thisopt
				and v.number = @thisopt
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
			if @bitdesc is not null
			begin
				if @dbdesc != ""
					select @dbdesc = @dbdesc + ", " +  @bitdesc
				else select @dbdesc = @bitdesc
			end

			/* Turn off this status bit in the options mask */
			select @optmask = @optmask & ~(@thisopt)
		end

		/*
		** Get the next option bit.  Check for integer overflow for
		** bit 31 (0x80000000).
		*/
		if (@thisopt < 1073741824)
			select @thisopt = @thisopt * 2
		else
			select @thisopt = -2147483648
	end

	/*
	**  Check status2 options (spt_values.type = "D2")
	*/
	select @thisopt = 1
	select @optmask = @all2opts	/* status2 options */
	while (@optmask != 0)		/* until all set options noted ... */
	begin
		/*
		** If this option is user-settable, check for it
		*/
		if (@optmask & @thisopt = @thisopt)
		begin
			select @bitdesc = null

			select @bitdesc = m.description
			from master.dbo.spt_values v,
			     master.dbo.sysdatabases d,
			     master.dbo.sysmessages m
			where d.dbid = @curdbid
				and v.type = "D2"
				and d.status2 & v.number = @thisopt
				and v.number = @thisopt
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
			if @bitdesc is not null
			begin
				if @dbdesc != ""
					select @dbdesc = @dbdesc + ", " +  @bitdesc
				else select @dbdesc = @bitdesc
			end

			/* Turn off this status bit in the options mask */
			select @optmask = @optmask & ~(@thisopt)
		end

		/*
		** Get the next option bit.  Check for integer overflow for
		** bit 31 (0x80000000).
		*/
		if (@thisopt < 1073741824)
			select @thisopt = @thisopt * 2
		else
			select @thisopt = -2147483648
	end

	/*
	**  If no flags are set, say so.
	*/
	if @dbdesc = ""
	begin
		/* 17591, "no options set" */
		exec sp_getmessage 17591, @dbdesc out
	end

	/*
	**  Save the description.
	*/
	update #spdbdesc
		set dbdesc = @dbdesc
			from #spdbdesc
				where dbid = @curdbid

	/*
	**  Now get the next, if any dbid.
	*/
	select @curdbid = min(dbid)
		from #spdbdesc
			where dbid > @curdbid
end 
	
/*	
** Compute number of Pages in a Megabyte.
*/
declare @numpgsmb 	float		/* Number of Pages per Megabyte */

select @numpgsmb = (1048576. / v.low)
	from master.dbo.spt_values v
		 where v.number = 1
		 and v.type = "E"	

/*
**  Now #spdbdesc is complete so we can print out the db info
*/
select distinct @len1 = max(datalength(d.name)),
		@len2 = max(datalength(l.name))
		from master.dbo.sysdatabases d, master.dbo.syslogins l, 
			master.dbo.sysusages u, #spdbdesc
		where d.dbid = #spdbdesc.dbid
			and d.suid = l.suid
			and #spdbdesc.dbid = u.dbid

if (@len1 > 24 or @len2 > 24)
	select distinct name = d.name,
		db_size = str(sum(u.size) / @numpgsmb, 10, 1)
			+ " MB",
		owner = l.name,
		dbid = d.dbid,
		created = convert(char(14), d.crdate, 107),
		status = #spdbdesc.dbdesc
			from master.dbo.sysdatabases d, master.dbo.syslogins l,
				 master.dbo.sysusages u, #spdbdesc
		where d.dbid = #spdbdesc.dbid
			and d.suid = l.suid
			and #spdbdesc.dbid = u.dbid
		group by #spdbdesc.dbid
		having d.dbid = #spdbdesc.dbid
			and d.suid = l.suid
			and #spdbdesc.dbid = u.dbid
		order by d.name
else
	select distinct name = convert(char(24), d.name),
		db_size = str(sum(u.size) / @numpgsmb, 10, 1)
			+ " MB",
		owner = convert(char(24), l.name),
		dbid = d.dbid,
		created = convert(char(14), d.crdate, 107),
		status = #spdbdesc.dbdesc
			from master.dbo.sysdatabases d, master.dbo.syslogins l,
				 master.dbo.sysusages u, #spdbdesc
		where d.dbid = #spdbdesc.dbid
			and d.suid = l.suid
			and #spdbdesc.dbid = u.dbid
		group by #spdbdesc.dbid
		having d.dbid = #spdbdesc.dbid
			and d.suid = l.suid
			and #spdbdesc.dbid = u.dbid
		order by d.name

/*  
** Print sysattributes data if there is any.  The join with multiple
** instances of sysattributes is to get the string descriptions for
** the class (master..sysattributes cn) and the attribute
** (master..sysattributes an). These should never be longer than
** 30 characters, so it's okay to truncate them.
*/

select name = db.name, attribute_class = convert(char(30),cn.char_value), 
	attribute = convert(char(30),an.char_value), a.int_value, 
	a.char_value, a.comments
into #spdbattr
from master.dbo.sysdatabases db, #spdbdesc d,
	master.dbo.sysattributes a, master.dbo.sysattributes an,
	master.dbo.sysattributes cn
where db.dbid = d.dbid
and a.class = cn.object
and a.attribute = an.object_info1
and a.class = an.object
and a.object_type = "D"
and a.object = d.dbid
and cn.class = 0
and cn.attribute = 0
and an.class = 0
and an.attribute = 1
and a.object = db.dbid

if exists (select * from #spdbattr)
begin
	select name, attribute_class, attribute, int_value, char_value,
		comments
	from #spdbattr
end


/*
**  If we are looking at one database, show its device allocation.
*/
if @showdev = 1
begin
	select @curdbid = dbid			/* database ID */
		from master.dbo.sysdatabases
		where name like @dbname
	select @pagekb = (low / 1024)		/* kbytes per page */
		from master.dbo.spt_values
		where number = 1
		  and type = 'E'

	/* Check the length of the usage column */
	select distinct @len3 = max(datalength(m.description))
	    from master.dbo.sysdatabases d, master.dbo.sysusages u, master.dbo.sysdevices v, master.dbo.spt_values a, 
			master.dbo.spt_values b, master.dbo.sysmessages m
		where d.dbid = u.dbid
			and v.low <= u.size + vstart
			and v.high >= u.size + vstart - 1
			and v.status & 2 = 2 
			and d.name = @dbname
			and a.type = "E"
			and a.number = 1
			and b.type = "S"
			and u.segmap & 7 = b.number
			and b.msgnum = m.error
			and isnull(m.langid, 0) = @sptlang

	if (@len3 > 20)

	    select device_fragments = v.name, size =
			str(size / @numpgsmb, 10, 1) + " MB",
		usage = m.description,
		(curunreservedpgs(@curdbid, u.lstart,
				u.unreservedpgs) * @pagekb) "free kbytes"
	    from master.dbo.sysdatabases d,
		 master.dbo.sysusages u,
		 master.dbo.sysdevices v,
		 master.dbo.spt_values a,
		 master.dbo.spt_values b,
		 master.dbo.sysmessages m
		where d.dbid = u.dbid
			and v.low <= u.size + vstart
			and v.high >= u.size + vstart - 1
			and v.status & 2 = 2 
			and d.name = @dbname
			and a.type = "E"
			and a.number = 1
			and b.type = "S"
			and u.segmap & 7 = b.number
			and b.msgnum = m.error
			and isnull(m.langid, 0) = @sptlang
	    order by 1

	else

	    select device_fragments = v.name, size =
		convert(varchar(10),
			round(
			(a.low * convert(float, u.size))
			/ 1048576, 1)) + " " + "MB",
		usage = convert(char(20), m.description),
		(curunreservedpgs(@curdbid, u.lstart,
				u.unreservedpgs) * @pagekb) "free kbytes"
	    from master.dbo.sysdatabases d,
		 master.dbo.sysusages u,
		 master.dbo.sysdevices v,
		 master.dbo.spt_values a,
		 master.dbo.spt_values b,
		 master.dbo.sysmessages m
		where d.dbid = u.dbid
			and v.low <= u.size + vstart
			and v.high >= u.size + vstart - 1
			and v.status & 2 = 2 
			and d.name = @dbname
			and a.type = "E"
			and a.number = 1
			and b.type = "S"
			and u.segmap & 7 = b.number
			and b.msgnum = m.error
			and isnull(m.langid, 0) = @sptlang
	    order by 1

	/*
	**  If there is only one database and we are in it, show the
	**  segments.
	*/
	if exists (select *
			from #spdbdesc
				where db_id() = dbid)
	begin
		declare @curdevice	varchar(30),
			@curseg		smallint,
			@segbit		int

		delete #spdbdesc

		select @curdevice = min(d.name)
			from  master.dbo.sysusages u, master.dbo.sysdevices d
				where u.dbid = db_id()
					and d.low <= size + vstart
					and d.high >= size + vstart - 1
					and d.status & 2 = 2 
		while (@curdevice is not null)
		begin
			/*
			** We need an inner loop here to go through
			**  all the possible segment.
			*/
			select @curseg = min(segment)
					from syssegments
			while (@curseg is not null)
			begin
				if (@curseg < 31)
					select @segbit = power(2, @curseg)
				else select @segbit = low
					from master.dbo.spt_values
						where type = "E"
							and number = 2
				insert into #spdbdesc
					select @curseg, @curdevice
						from master.dbo.sysusages u,
							master.dbo.sysdevices d,
							master.dbo.spt_values v
					where u.segmap & @segbit = @segbit
						and d.low <= u.size + u.vstart
						and d.high >= u.size + u.vstart - 1
						and u.dbid = db_id()
						and d.status & 2 = 2 
						and v.number = 1
						and v.type = "E"
						and d.name = @curdevice
				select @curseg = min(segment)
						from syssegments
							where segment > @curseg
			end

			select @curdevice = min(d.name)
				from  master.dbo.sysusages u,
					master.dbo.sysdevices d
				where u.dbid = db_id()
					and d.low <= size + vstart
					and d.high >= size + vstart - 1
					and d.status & 2 = 2 
					and d.name > @curdevice
		end

		/*
		**  One last check for any devices that have no segments.
		*/
		insert into #spdbdesc
			select null, d.name
				from master.dbo.sysusages u,
					master.dbo.sysdevices d
			where u.segmap = 0
				and d.low <= u.size + u.vstart
				and d.high >= u.size + u.vstart - 1
				and u.dbid = db_id()
				and d.status & 2 = 2 

		/* 17592, " -- unused by any segments --" */
		exec sp_getmessage 17592, @msg out


		select distinct @len1 = max(datalength(dbdesc))
			from #spdbdesc, syssegments
				where dbid *= segment

		if (@len1 > 30)
			select distinct device = dbdesc,
				segment = isnull(name, @msg)
			from #spdbdesc, syssegments
				where dbid *= segment
				order by 1, 2
		else
			select distinct device = convert(char(30), dbdesc),
				segment = isnull(name, @msg)
			from #spdbdesc, syssegments
				where dbid *= segment
				order by 1, 2
	end

end

drop table #spdbdesc
drop table #spdbattr
return (0)
go
exec sp_procxmode 'sp_helpdb', 'anymode'
go
grant execute on sp_helpdb to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpdevice')
begin
	drop procedure sp_helpdevice
end
go
print "Installing sp_helpdevice"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helpdevice"         17610
**
** 17610, "No such i/o device exists."
** 17611, "special"
** 17612, "disk"
** 17613, "tape"
** 17614, "UNKNOWN DEVICE"
** 17615, "MIRROR ENABLED"
** 17616, "MIRROR DISABLED"
** 17617, "mirror = "
** 17618, "only device '%1!' of mirror is enabled -- device '%2!' is disabled"
** 17619, "channel"
** 17620, "nonserial writes"
*/
create procedure sp_helpdevice
@devname varchar(30) = "%"		/* device to check out */
as

declare @tapeblocksize int

declare @msg varchar(90)
declare @sptlang	int
declare @length		int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @sptlang = @@langid

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17120 and 17129
		and langid = @@langid)
	    select @sptlang = 0
end

/*
**  See if the device exists.
*/
if not exists (select *
			from master.dbo.sysdevices
				where name like @devname)
begin
	/* 17610, "No such i/o device exists." */
	exec sp_getmessage 17610, @msg out
	print @msg
	return (1)
end

/*
**  Create a temporary table where we can build up a translation of
**  the device status bits.
*/
create table #spdevtab
(
	name varchar(30),
	statusdesc varchar(250) null
)

set nocount on

/*
**  Initialize the temporary table with the names of the devices.
*/
insert into #spdevtab (name)
	select name
		from master.dbo.sysdevices
			where name like @devname


/*
**  Now figure out what kind of controller type it is.  The type are
**  COMPLETELY machine dependent and are for UNIX.
**  cntrltype = 0	special
**	        2	disk
**	      3-8	tape
**	      9-14	channel
*/

/* 17611, "special" */
exec sp_getmessage 17611, @msg out
update #spdevtab
	set statusdesc = @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.cntrltype = 0
				and #spdevtab.name = d.name

/* 17612, "disk" */
exec sp_getmessage 17612, @msg out
update #spdevtab
	set statusdesc = @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.cntrltype = 2
				and #spdevtab.name = d.name

/* 17613, "tape" */
exec sp_getmessage 17613, @msg out
update #spdevtab
	set statusdesc = @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.cntrltype >= 3 and d.cntrltype <= 8
				and #spdevtab.name = d.name
/* 17619, "channel" */
exec sp_getmessage 17619, @msg out
update #spdevtab
	set statusdesc = @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.cntrltype >= 9 and d.cntrltype <= 14
				and #spdevtab.name = d.name

/*
**  If a tape device, also figure out the tape capacity which is listed
**  in sysdevices.high in number of 32k blocks.
*/
if exists (select *
		from master.dbo.sysdevices d, #spdevtab
			where d.cntrltype >= 3 and d.cntrltype <= 8
				and d.high > 0
				and #spdevtab.name = d.name)
begin
        /*
        ** Find size of tape block.  Default to 32k.
        */

        select @tapeblocksize = low
                from master.dbo.spt_values
                        where type = "E"
                                and number = 4
        if @tapeblocksize is NULL
        begin
                select @tapeblocksize = 32768
        end

	update #spdevtab
		set statusdesc = statusdesc + ", " + str(round((d.high *
                                convert(float, @tapeblocksize)) / 1048576., 0))
			+ " MB"
		from master.dbo.sysdevices d, #spdevtab
			where d.cntrltype >= 3 and d.cntrltype <= 8
				and d.high > 0
				and #spdevtab.name = d.name
end

/* 17614, "UNKNOWN DEVICE" */
exec sp_getmessage 17614, @msg out
update #spdevtab
	set statusdesc = @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.cntrltype > 14
				and #spdevtab.name = d.name

/*
**  Now check out the status bits and turn them into english.
**  The mirror status bits are >= 32.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status >= 32
			and d.status & 256 != 256
			and #spdevtab.name = d.name)
begin
	/*
	**  Check to see if the mirror is enabled. 0x200 (512) bit in status.
	*/
	if exists (select *
		from master.dbo.sysdevices d, #spdevtab
			where d.status & 512 = 512
				and #spdevtab.name = d.name)
	begin
		/* 17615, "MIRROR ENABLED" */
		exec sp_getmessage 17615, @msg out
		update #spdevtab
			set statusdesc = statusdesc + ", " + @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.status & 512 = 512
				and #spdevtab.name = d.name
	end

	if exists (select *
		from master.dbo.sysdevices d, #spdevtab
			where d.status & 512 != 512
				and d.status >= 32
				and #spdevtab.name = d.name)
	begin
		/* 17616, "MIRROR DISABLED" */
		exec sp_getmessage 17616, @msg out
		update #spdevtab
			set statusdesc = statusdesc + ", " + @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.status & 512 != 512
				and d.status >= 32
				and #spdevtab.name = d.name
	end

	/* add mirror name */
	/* 17617, "mirror = " */
	exec sp_getmessage 17617, @msg out
	update #spdevtab
		set statusdesc = statusdesc + ", " + @msg + " '" + d.mirrorname
			+ "'"
		from master.dbo.sysdevices d, #spdevtab
			where #spdevtab.name = d.name
				and d.status >= 32
end

/*
**  Check to see if there is a mirrorname entry but mirroring not enabled.
**  If so, then one side of the mirror is off-line.
*/
else if exists (select *
	from master.dbo.sysdevices d, #spdevtab
		where #spdevtab.name = d.name
		and d.status & 256 = 256
		and d.mirrorname is not null)
begin
	/* Set up the message */
	declare @part1	varchar(60)
	declare @part2	varchar(60)
	declare @part3	varchar(60)
	/* 17618, "only device '%1!' of mirror is enabled -- device '%2!'
	**	is disabled"
	*/
	exec sp_getmessage 17618, @msg out
	select @part1 = substring(@msg, 1, charindex("%1!", @msg) - 1)
	select @part2 = substring(@msg, charindex("%1!", @msg) + 3, 
		((charindex("%2!", @msg) - 1) - (charindex("%1!", @msg) +2)))
	select @part3 = substring(@msg, charindex("%2!", @msg) + 3, 60)

	/*
	**  Figure out which side of the mirror is disabled.
	**  If 0x100 is on then phyname is disabled and mirrorname is enabled.
	*/
	if exists (select *
		from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
			where v.type = "V" and v.number > -1
				and d.status & v.number = 256
				and #spdevtab.name = d.name)
	begin
		update #spdevtab
			set statusdesc = @part1 + d.mirrorname 
				+ @part2 + d.phyname + @part3
			from master.dbo.sysdevices d, master.dbo.spt_values v,
				#spdevtab
			where v.type = "V" and v.number > -1
				and d.status & v.number = 256
				and #spdevtab.name = d.name
	end
	else if exists (select *
		from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
			where v.type = "V" and v.number > -1
				and d.status & v.number = 64
				and #spdevtab.name = d.name)
	begin
		update #spdevtab
			set statusdesc = @part1 + d.phyname 
				+ @part2 + d.mirrorname + @part3
			from master.dbo.sysdevices d, master.dbo.sysdevices e,
				master.dbo.spt_values v, #spdevtab
			where v.type = "V" and v.number > -1
				and d.status & v.number = 64
				and #spdevtab.name = d.name
				and e.status & 256 != 256
				and #spdevtab.name = e.name
	end
end


/*
**  Status of 0x20 is "serial writes" for mirrored disks.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status & v.number = 32
			and #spdevtab.name = d.name)
begin
	update #spdevtab
		set statusdesc = statusdesc + ", " + m.description
		from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab,
				master.dbo.sysmessages m
			where v.type = "V" and v.number > -1
				and d.status & v.number = 32
				and #spdevtab.name = d.name
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
end

/* 17620, "nonserial writes" */
exec sp_getmessage 17620, @msg out
update #spdevtab
	set statusdesc = statusdesc + ", " + @msg
		from master.dbo.sysdevices d, #spdevtab
			where d.status > 32
				and d.status &32 != 32
				and #spdevtab.name = d.name

/*
**  Status of 0x80 is "reads mirrored" for mirrored disks.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status & v.number = 128
			and #spdevtab.name = d.name)
begin
	update #spdevtab
		set statusdesc = statusdesc + ", " + m.description
		from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab,
				master.dbo.sysmessages m
			where v.type = "V" and v.number > -1
				and d.status & v.number = 128
				and #spdevtab.name = d.name
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
end

/*
**  Now check out the status bits and turn them into english.
**  Status of 0x10 is a dump device.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status & v.number = 16
			and #spdevtab.name = d.name)
begin
	update #spdevtab
		set statusdesc = statusdesc + ", " + m.description
		from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab,
				master.dbo.sysmessages m
			where v.type = "V" and v.number > -1
				and d.status & v.number = 16
				and #spdevtab.name = d.name
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
end

/*
**  Now check out the status bits and turn them into english.
**  Status of 0x01 is a default disk.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status & v.number = 1
			and #spdevtab.name = d.name)
begin
	update #spdevtab
		set statusdesc = statusdesc + ", " + m.description
		from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab,
				master.dbo.sysmessages m
			where v.type = "V" and v.number > -1
				and d.status & v.number = 1
				and #spdevtab.name = d.name
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
end

/*
**  Now check out the status bits and turn them into english.
**  Status of 0x02 is a physical disk.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status & v.number = 2
			and #spdevtab.name = d.name)
begin
	update #spdevtab
		set statusdesc = statusdesc + ", " + m.description
		from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab,
				master.dbo.sysmessages m
			where v.type = "V" and v.number > -1
				and d.status & v.number = 2
				and #spdevtab.name = d.name
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang

	/*
	** Compute number of Pages in a Megabyte.
	*/
	declare @numpgsmb float		/* Number of Pages per Megabytes */

	select @numpgsmb = (1048576. / v.low)
		from master.dbo.spt_values v
			where v.number = 1
				and v.type = "E"

	/*
	**  Add in its size in MB.
	*/
	update #spdevtab
		set statusdesc = statusdesc + ", " +
			ltrim(str((1. + (d.high - d.low)) / @numpgsmb, 10, 2)) + " MB"
		from master.dbo.sysdevices d, #spdevtab
			where d.status & 2 = 2
				and #spdevtab.name = d.name
end

/*
**  Now check out the status bits and turn them into english.
**  Status of 0x04 is a logical disk.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status & v.number = 4
			and #spdevtab.name = d.name)
begin
	update #spdevtab
		set statusdesc = statusdesc + ", " + m.description
		from master.dbo.sysdevices d, master.dbo.spt_values v, 
				#spdevtab, master.dbo.sysmessages m
			where v.type = "V" and v.number > -1
				and d.status & v.number = 4
				and #spdevtab.name = d.name
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
end

/*
**  Now check out the status bits and turn them into english.
**  Status of 0x08 is a skip tape header.
*/
if exists (select *
	from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
		where v.type = "V" and v.number > -1
			and d.status & v.number = 8
			and #spdevtab.name = d.name)
begin
	update #spdevtab
		set statusdesc = statusdesc + ", " + m.description
		from master.dbo.sysdevices d, master.dbo.spt_values v, 
				#spdevtab, master.dbo.sysmessages m
			where v.type = "V" and v.number > -1
				and d.status & v.number = 8
				and #spdevtab.name = d.name
				and v.msgnum = m.error
				and isnull(m.langid, 0) = @sptlang
end

set nocount off

/*
**  The device number is in the high byte of sysdevices.low so
**  spt_values tells us which byte to pick out.
*/

select @length = max(datalength(d.phyname))
	from master.dbo.sysdevices d, #spdevtab
	where d.name = #spdevtab.name

if (@length > 46)
    select device_name = d.name,
	physical_name = d.phyname,
	description = #spdevtab.statusdesc,
	d.status, d.cntrltype,
	device_number = convert(tinyint, substring(convert(binary(4), d.low),
		v.low, 1)),
	low = (convert(tinyint, substring(convert(binary(4), d.low), v.low,
		1))) * floor(power(2.0,24)),
	high = (convert(tinyint, substring(convert(binary(4), d.low), v.low,
		1))) * floor(power(2.0,24)) + (d.high - d.low)
		from master.dbo.sysdevices d, #spdevtab,
		     master.dbo.spt_values v
		where d.name = #spdevtab.name
		     and v.type = "E" and v.number = 3
else
    select device_name = d.name,
	physical_name = convert(char(46), d.phyname),
	description = #spdevtab.statusdesc,
	d.status, d.cntrltype,
	device_number = convert(tinyint, substring(convert(binary(4), d.low),
		v.low, 1)),
	low = (convert(tinyint, substring(convert(binary(4), d.low), v.low,
		1))) * floor(power(2.0,24)),
	high = (convert(tinyint, substring(convert(binary(4), d.low), v.low,
		1))) * floor(power(2.0,24)) + (d.high - d.low)
		from master.dbo.sysdevices d, #spdevtab,
		     master.dbo.spt_values v
		where d.name = #spdevtab.name
		     and v.type = "E" and v.number = 3

return (0)
go
exec sp_procxmode 'sp_helpdevice', 'anymode'
go
grant execute on sp_helpdevice to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helplog')
begin
	drop procedure sp_helplog
end
go
print "Installing sp_helplog"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */
/*
** Messages for "sp_helplog"            17672
**
** 17672, "In database '%1!', the log starts on device '%2!'."
** 18433, "No valid log device can be found to contain the starting logpage 
**	   of '%1!', on database '%2!'. Perhaps the segment mapping of 
**	   database has changed recently.  Please inspect the sysusages 
**	   catalog and contact your system administrator."
**
*/
create procedure sp_helplog
as
declare @firstpage int,
	@devname varchar(255),
	@msg varchar(255),
	@dbname varchar(255)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* Get the first page of the log from sysindexes */
select @firstpage = first
	from sysindexes
		where id = 8

/*
**  Get the name of the device which contains the first page of the log.
**  Make sure that the device has logsegment mapped to it. The device number 
**  is in the high byte of d.low and u.vstart and which is the high byte is 
**  defined in spt_values.
*/
select @devname = d.name 
	from master.dbo.sysdevices d, master.dbo.sysusages u,
		master.dbo.spt_values v
	where (d.status & 2 = 2 or d.status & 4 = 4) 
		and @firstpage >= u.lstart
		and @firstpage < u.lstart + u.size - 1
		and convert(tinyint, substring(convert(binary(4), d.low),
			v.low, 1))
		  = convert(tinyint, substring(convert(binary(4), u.vstart),
		       v.low, 1))
		and v.type = "E"
		and v.number = 3
		and u.dbid = db_id()
		and u.segmap & 4 = 4

select @dbname = db_name()
 
if (@devname is NULL)
begin

	/* 
	** 18433, "No valid log device can be found to contain the starting 
	**	  logpage of '%1!', on database '%2!'. Perhaps the segment 
	**	  mapping of database has changed recently.  Please inspect 
	**	  the sysusages catalog and contact your system administrator."
	*/
	exec sp_getmessage 18433, @msg out
	print @msg, @firstpage, @dbname
end
else
begin
	/* Print the name of the device which contains the log start page */
	/* 17672, "In database '%1!', the log starts on device '%2!'." */
	exec sp_getmessage 17672, @msg out
	print @msg, @dbname, @devname
end

return (0)
go
exec sp_procxmode 'sp_helplog', 'anymode'
go
grant execute on sp_helplog to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpindex')
begin
	drop procedure sp_helpindex
end
go
print "Installing sp_helpindex"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helpindex"          17640
**
** 17460, "Object must be in the current database."
** 17461, "Object does not exist in this database."
** 17640, "Object does not have any indexes."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_helpindex
@objname varchar(92)			/* the table to check for indexes */
as

declare @indid int			/* the index id of an index */
declare @keys varchar(200)		/* string to build up index key in */
declare @inddesc varchar(68)		/* string to build up index desc in */
declare @msg varchar(90)
declare @len1 int, @len2 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see that the object names are local to the current database.
*/
if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
begin
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return (1)
end

/*
**  Check to see the the table exists 
*/
if not exists (select id
		from sysobjects
			where id = object_id(@objname))
/*
**  Table doesn't exist so return.
*/
begin
	/* 17461, "Object does not exist in this database." */
	exec sp_getmessage 17461, @msg out
	print @msg
	return (1)
end

/*
**  See if the object has any indexes.
**  Since there may be more than one entry in sysindexes for the object,
**  this select will set @indid to the index id of the first index.
*/
select @indid = min(indid)
	from sysindexes
		where id = object_id(@objname)
			and indid > 0
			and indid < 255

/*
**  If no indexes, return.
*/
if @indid is NULL
begin
	/* 17640, "Object does not have any indexes." */
	exec sp_getmessage 17640, @msg out
	print @msg
	return (1)
end

/*
**  Now check out each index, figure out it's type and keys and
**  save the info in a temporary table that we'll print out at the end.
*/
create table #spindtab
(
	index_name	varchar(30),
	index_keys	varchar(255),
	index_description	varchar(68),
	index_max_rows_per_page	smallint
)

/*  Create temporary table for sysattributes data */
create table #spindattr
(
	name		varchar(30), 
	class		smallint,
	attribute	smallint,
	int_value	int NULL,
	char_value	varchar(255) NULL,
	comments	varchar(255) NULL
)

while @indid is not NULL
begin
	
	/*
	**  First we'll figure out what the keys are.
	*/
	declare @i int
	declare @thiskey varchar(30)
	declare @lastindid int

	select @keys = "", @i = 1

	set nocount on

	while @i <= 16
	begin
		select @thiskey = index_col(@objname, @indid, @i)

		if @thiskey is NULL
		begin
			goto keysdone
		end

		if @i > 1
		begin
			select @keys = @keys + ", "
		end

		select @keys = @keys + index_col(@objname, @indid, @i)

		/*
		**  Increment @i so it will check for the next key.
		*/
		select @i = @i + 1

	end


	/*
	**  When we get here we now have all the keys.
	*/
	keysdone:
		set nocount off

	/*
	**  Initialize the index description by figuring out if it's a
	**  clustered or nonclustered index.
	*/
	if @indid = 1
	begin
		select @inddesc = "clustered"
	end
	if @indid > 1
	begin
		select @inddesc = "nonclustered"
	end

	/*
	**  Now we'll check out the status bits for this index and
	**  build an english description from them.
	*/

	/*
	**  See if the index is unique (0x02).
	*/
	if exists (select *
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 2
				and i.id = object_id(@objname)
				and i.indid = @indid)
	begin
	select @inddesc = @inddesc + ", " + v.name
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 2
				and i.id = object_id(@objname)
				and i.indid = @indid
	end

	/*
	**  See if the index is ignore_dupkey (0x01).
	*/
	if exists (select *
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 1
				and i.id = object_id(@objname)
				and i.indid = @indid)
	begin
	select @inddesc = @inddesc + ", " + v.name
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 1
				and i.id = object_id(@objname)
				and i.indid = @indid
	end

	/*
	**  See if the index is ignore_dup_row (0x04).
	*/
	if exists (select *
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 4
				and i.id = object_id(@objname)
				and i.indid = @indid)
	begin
	select @inddesc = @inddesc + ", " + v.name
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 4
				and i.id = object_id(@objname)
				and i.indid = @indid
	end

	/*
	**  See if the index is allow_dup_row (0x40).
	*/
	if exists (select *
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 64
				and i.id = object_id(@objname)
				and i.indid = @indid)
	begin
	select @inddesc = @inddesc + ", " + v.name   
		from master.dbo.spt_values v, sysindexes i
			where i.status & v.number = v.number
				and v.type = "I"
				and v.number = 64
				and i.id = object_id(@objname)
				and i.indid = @indid
	end

	/*
	**  Add the location of the data.
	*/
	select @inddesc = @inddesc + " located on " + s.name
		from syssegments s, sysindexes i
			where s.segment = i.segment
				and i.id = object_id(@objname)
				and i.indid = @indid

	/*
	**  Now we have the whole description for the index so we'll add
	**  the goods to the temporary table.
	*/
	insert into #spindtab
		select name, @keys, @inddesc, maxrowsperpage
			from sysindexes
				where id = object_id(@objname)
					and indid = @indid
	/* 
	**  Get sysattributes data if there is any
	*/
	insert #spindattr (name, class, attribute, int_value, char_value, 
								comments)
		select i.name, a.class, a.attribute, a.int_value, a.char_value,
								a.comments
		from sysindexes i, sysattributes a
		where a.object_type = "I"
		and a.object = object_id(@objname)
		and a.object_info1 = @indid
		and i.id = object_id(@objname)
		and i.indid = @indid

	/*
	**  Now move @indid to the next index.
	*/
	select @lastindid = @indid
	select @indid = NULL
	select @indid = min(indid)
		from sysindexes
			where id = object_id(@objname)
				and indid > @lastindid
				and indid < 255
end

/*
**  Now print out the contents of the temporary index table.
*/
select @len1 = max(datalength(index_name)),
       @len2 = max(datalength(index_description))
	from #spindtab

if (@len1 > 20 or @len2 > 56)
    select index_name = index_name,
	index_description = index_description,
	index_keys = index_keys,
	index_max_rows_per_page = index_max_rows_per_page from #spindtab
else
    select index_name = convert(char(20), index_name),
	index_description = convert(char(56), index_description),
	index_keys = index_keys,
	index_max_rows_per_page = index_max_rows_per_page from #spindtab

drop table #spindtab

/*  
** Print sysattributes data if there is any.  The join with
** master..sysattributes is to get the string descriptions for the
** class (master.dbo.sysattributes cn) and attribute
** (master.dbo.sysattributes an). These should never be more than
** 30 characters, so it's okay to truncate them to 30.
*/

if exists (select * from #spindattr)
begin 
	select name = a.name, attribute_class = convert(char(30),cn.char_value),
		attribute = convert(char(30),an.char_value), a.int_value, 
		a.char_value, a.comments
	from #spindattr a, master.dbo.sysattributes cn,
		master.dbo.sysattributes an
	where a.class = cn.object
	and a.attribute = an.object_info1
	and a.class = an.object
	and cn.class = 0
	and cn.attribute = 0
	and an.class = 0
	and an.attribute = 1
end
drop table #spindattr
return (0)
go
exec sp_procxmode 'sp_helpindex', 'anymode'
go
grant execute on sp_helpindex to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpjoins')
begin
	drop procedure sp_helpjoins
end
go
print "Installing sp_helpjoins"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helpjoins"          17650
**
** 17460, "Object must be in the current database."
** 17650, "First table doesn't exist."
** 17651, "Second table doesn't exist."
** 17652, "Object must be in your current database."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_helpjoins
@lefttab varchar(92),			/* name of first table to join */
@righttab varchar(92)			/* name of first table to join */
as

declare @foundit bit			/* flag to indicate joins found */
declare @msg varchar(90)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  This procedure returns any foreign or common joins.
**  If none exists, then it returns any joins that have the same usertype.
**  If none exists, it returns any joins that have the same physical type.
*/

/*
**  Make sure the @objname is local to the current database.
*/
if @lefttab like "%.%.%" and
	substring(@lefttab, 1, charindex(".", @lefttab) - 1) != db_name()
begin
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return (1)
end
if @righttab like "%.%.%" and
	substring(@righttab, 1, charindex(".", @righttab) - 1) != db_name()
begin
	/*
	** 17652, "Object must be in your current database."
	*/
	exec sp_getmessage 17652, @msg output
	print @msg
	return (1)
end

/*
**  See if we can find the objects.  They must be a system table, user table,
**  or view.  The low 3 bits of sysobjects.sysstat indicate what the 
**  object type is -- it's more reliable than using sysobjects.type which
**  could change.
*/
/*
**  If either of the tables don't exist, quit.
*/
if not exists (select id
	from sysobjects
		where id = object_id(@lefttab)
			and (sysstat & 7 = 1		/* system table */
				or sysstat & 7 = 2	/* view */
				or sysstat & 7 = 3))	/* user table */
begin
	/* 17650, "First table doesn't exist." */
	exec sp_getmessage 17650, @msg out
	print @msg
	return (1)
end 

if not exists (select id
	from sysobjects
		where id = object_id(@righttab)
			and (sysstat & 7 = 1		/* system table */
				or sysstat & 7 = 2	/* view */
				or sysstat & 7 = 3))	/* user table */

begin
	/* 17651, "Second table doesn't exist." */
	exec sp_getmessage 17651, @msg out
	print @msg
	return (1)
end 

create table #hjtab
(
	a1	varchar(30),
	a2	varchar(30),
	b1	varchar(30) null,
	b2	varchar(30) null,
	c1	varchar(30) null,
	c2	varchar(30) null,
	d1	varchar(30) null,
	d2	varchar(30) null,
	e1	varchar(30) null,
	e2	varchar(30) null,
	f1	varchar(30) null,
	f2	varchar(30) null,
	g1	varchar(30) null,
	g2	varchar(30) null,
	h1	varchar(30) null,
	h2	varchar(30) null
)

/*
**  Look for foreign key joins.
*/
select @foundit = 0
if exists (select *
		from syskeys
			where type = 2
				and id = object_id(@lefttab)
				and depid = object_id(@righttab))
begin
	insert into #hjtab
	select distinct first_pair = col_name(id, key1), col_name(depid, depkey1),
		second_pair = col_name(id, key2), col_name(depid, depkey2),
		third_pair = col_name(id, key3), col_name(depid, depkey3),
		fourth_pair = col_name(id, key4), col_name(depid, depkey4),
		fifth_pair = col_name(id, key5), col_name(depid, depkey5),
		sixth_pair = col_name(id, key6), col_name(depid, depkey6),
		seventh_pair = col_name(id, key7), col_name(depid, depkey7),
		eighth_pair = col_name(id, key8), col_name(depid, depkey8)
	from syskeys
		where type = 2
			and id = object_id(@lefttab)
			and depid = object_id(@righttab)

	select @foundit = 1
end

if exists (select *
		from syskeys
			where type = 2
				and id = object_id(@righttab)
				and depid = object_id(@lefttab))
begin
	insert into #hjtab
	select distinct first_pair = col_name(depid, depkey1), col_name(id, key1),
		second_pair = col_name(depid, depkey2), col_name(id, key2),
		third_pair = col_name(depid, depkey3), col_name(id, key3),
		fourth_pair = col_name(depid, depkey4), col_name(id, key4),
		fifth_pair = col_name(depid, depkey5), col_name(id, key5),
		sixth_pair = col_name(depid, depkey6), col_name(id, key6),
		seventh_pair = col_name(depid, depkey7), col_name(id, key7),
		eighth_pair = col_name(depid, depkey8), col_name(id, key8)
	from syskeys
		where type = 2
			and id = object_id(@righttab)
			and depid = object_id(@lefttab)

	select @foundit = 1
end

/*
**  Look for common key joins.
*/
if exists (select *
		from syskeys
			where type = 3
				and id = object_id(@lefttab)
				and depid = object_id(@righttab))
begin
	insert into #hjtab
	select distinct first_pair = col_name(id, key1), col_name(depid, depkey1),
		second_pair = col_name(id, key2), col_name(depid, depkey2),
		third_pair = col_name(id, key3), col_name(depid, depkey3),
		fourth_pair = col_name(id, key4), col_name(depid, depkey4),
		fifth_pair = col_name(id, key5), col_name(depid, depkey5),
		sixth_pair = col_name(id, key6), col_name(depid, depkey6),
		seventh_pair = col_name(id, key7), col_name(depid, depkey7),
		eighth_pair = col_name(id, key8), col_name(depid, depkey8)
	from syskeys
		where type = 3
			and id = object_id(@lefttab)
			and depid = object_id(@righttab)

	select @foundit = 1
end

if exists (select *
		from syskeys
			where type = 3
				and id = object_id(@righttab)
				and depid = object_id(@lefttab))
begin
	insert into #hjtab
	select distinct first_pair = col_name(depid, depkey1), col_name(id, key1),
		second_pair = col_name(depid, depkey2), col_name(id, key2),
		third_pair = col_name(depid, depkey3), col_name(id, key3),
		fourth_pair = col_name(depid, depkey4), col_name(id, key4),
		fifth_pair = col_name(depid, depkey5), col_name(id, key5),
		sixth_pair = col_name(depid, depkey6), col_name(id, key6),
		seventh_pair = col_name(depid, depkey7), col_name(id, key7),
		eighth_pair = col_name(depid, depkey8), col_name(id, key8)
	from syskeys
		where type = 3
			and id = object_id(@righttab)
			and depid = object_id(@lefttab)

	select @foundit = 1
end

/*
**  We got a foreignkey and we didn't get a common key.
*/
if @foundit = 1
begin
	select distinct *
		from #hjtab

	drop table #hjtab

	return (0)
end

/*
**  We didn't find any defined joins so we'll look for common user types.
*/
if exists (select *
		from syscolumns a, syscolumns b
			where a.id = object_id(@lefttab)
				and b.id = object_id(@righttab)
				and a.usertype = b.usertype
				and a.usertype > 99)
begin
	select distinct first_pair = col_name(a.id, a.colid),
		col_name(b.id, b.colid)
	from syscolumns a, syscolumns b
		where a.id = object_id(@lefttab)
			and b.id = object_id(@righttab)
			and a.usertype = b.usertype
			and a.usertype > 99
	order by first_pair

	/*
	**  If we found something, we can stop.
	*/
	if @@rowcount > 0
		return (0)
end

/*
**  We couldn't find anything so far so we'll see if we have anything
**  that just shares the same physical type.
*/
if exists (select *
		from syscolumns a, syscolumns b, master.dbo.spt_values y,
			master.dbo.spt_values z
		where a.id = object_id(@lefttab)
			and b.id = object_id(@righttab)
			and a.id != b.id
			and a.name = b.name
			and y.type = "J"
			and a.type = y.low
			and z.type = "J"
			and b.type = z.low
			and y.number = z.number)
begin
	select distinct first_pair = col_name(a.id, a.colid),
		col_name(b.id, b.colid)
	from syscolumns a, syscolumns b, master.dbo.spt_values y,
		master.dbo.spt_values z
	where a.id = object_id(@lefttab)
		and b.id = object_id(@righttab)
		and a.id != b.id
		and a.name = b.name
		and y.type = "J"
		and a.type = y.low
		and z.type = "J"
		and b.type = z.low
		and y.number = z.number
	order by first_pair

end

return (0)
go
exec sp_procxmode 'sp_helpjoins', 'anymode'
go
grant execute on sp_helpjoins to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpkey')
begin
	drop procedure sp_helpkey
end
go
print "Installing sp_helpkey"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helpkey"            17660
**
** 17390, "Table or view name must be in 'current' database."
** 17492, "The table or view named doesn't exist in the current database."
** 17660, "No defined keys for this object."
** 17661, " -- none --"
** 17662, "NOTE : For information on declarative integrity features : PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK CONSTRAINT, REFERENTIAL CONSTRAINT, NULL/NOT NULL, and DEFAULT, use sp_helpconstr, a new system stored procedure."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_helpkey
@tabname varchar(92) = null	/* table or view we want to check */
as

declare @note	varchar(255)
declare @msg	varchar(90)
declare @none	varchar(30)
declare @len1 int, @len2 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see that the object names are local to the current database.
*/
if @tabname like "%.%.%" and
	substring(@tabname, 1, charindex(".", @tabname) - 1) != db_name()
begin
	/* 17390, "Table or view name must be in 'current' database." */
	exec sp_getmessage 17390, @msg out
	print @msg
	return (1)
end

/*
** This procedure should eventually become obsolete since with System 10
** we support declarative constraints.  This constraint information is
** available through sp_helpconstr.  The server will not record any information
** in syskeys.  Do this only if this procedure is executed directly.
*/
if @@nestlevel = 1
begin
	exec sp_getmessage 17662, @note out
	print @note
	print ""
end

exec sp_getmessage 17661, @none out

/*
**  If @tabname is null, show all the keys.
*/
if @tabname is null
begin
    select @len1 = max(datalength(col_name(k.id, key1) + ", "
			+ isnull(col_name(k.id, key2), "*") + ", "
			+ isnull(col_name(k.id, key3), "*") + ", "
			+ isnull(col_name(k.id, key4), "*") + ", "
			+ isnull(col_name(k.id, key5), "*") + ", "
			+ isnull(col_name(k.id, key6), "*") + ", "
			+ isnull(col_name(k.id, key7), "*") + ", "
			+ isnull(col_name(k.id, key8), "*"))),
	   @len2 = max(datalength(
			  isnull(col_name(k.depid, depkey1), "*") + ", "
			+ isnull(col_name(k.depid, depkey2), "*") + ", "
			+ isnull(col_name(k.depid, depkey3), "*") + ", "
			+ isnull(col_name(k.depid, depkey4), "*") + ", "
			+ isnull(col_name(k.depid, depkey5), "*") + ", "
			+ isnull(col_name(k.depid, depkey6), "*") + ", "
			+ isnull(col_name(k.depid, depkey7), "*") + ", "
			+ isnull(col_name(k.depid, depkey8), "*")))
		from syskeys k

    if (@len1 > 70 or @len2 > 70)
	select keytype = convert(char(10), v.name), object = object_name(k.id),
		related_object = isnull(object_name(k.depid), @none),
		object_keys = 	 col_name(k.id, key1) + ", "
			+ isnull(col_name(k.id, key2), "*") + ", "
			+ isnull(col_name(k.id, key3), "*") + ", "
			+ isnull(col_name(k.id, key4), "*") + ", "
			+ isnull(col_name(k.id, key5), "*") + ", "
			+ isnull(col_name(k.id, key6), "*") + ", "
			+ isnull(col_name(k.id, key7), "*") + ", "
			+ isnull(col_name(k.id, key8), "*"),
		related_keys = 
			  isnull(col_name(k.depid, depkey1), "*") + ", "
			+ isnull(col_name(k.depid, depkey2), "*") + ", "
			+ isnull(col_name(k.depid, depkey3), "*") + ", "
			+ isnull(col_name(k.depid, depkey4), "*") + ", "
			+ isnull(col_name(k.depid, depkey5), "*") + ", "
			+ isnull(col_name(k.depid, depkey6), "*") + ", "
			+ isnull(col_name(k.depid, depkey7), "*") + ", "
			+ isnull(col_name(k.depid, depkey8), "*")
	from syskeys k, master.dbo.spt_values v
		where k.type = v.number and v.type = 'K'
	order by object, keytype, related_object
    else
	select keytype = convert(char(10), v.name), object = object_name(k.id),
		related_object = isnull(object_name(k.depid), @none),
		object_keys = convert(char(70), 
				 col_name(k.id, key1) + ", "
			+ isnull(col_name(k.id, key2), "*") + ", "
			+ isnull(col_name(k.id, key3), "*") + ", "
			+ isnull(col_name(k.id, key4), "*") + ", "
			+ isnull(col_name(k.id, key5), "*") + ", "
			+ isnull(col_name(k.id, key6), "*") + ", "
			+ isnull(col_name(k.id, key7), "*") + ", "
			+ isnull(col_name(k.id, key8), "*")),
		related_keys = convert(char(70), 
			  isnull(col_name(k.depid, depkey1), "*") + ", "
			+ isnull(col_name(k.depid, depkey2), "*") + ", "
			+ isnull(col_name(k.depid, depkey3), "*") + ", "
			+ isnull(col_name(k.depid, depkey4), "*") + ", "
			+ isnull(col_name(k.depid, depkey5), "*") + ", "
			+ isnull(col_name(k.depid, depkey6), "*") + ", "
			+ isnull(col_name(k.depid, depkey7), "*") + ", "
			+ isnull(col_name(k.depid, depkey8), "*"))
	from syskeys k, master.dbo.spt_values v
		where k.type = v.number and v.type = 'K'
	order by object, keytype, related_object

	return (0)
end

/*
**  We're looking for a particular table or view.
*/
else
begin
	/*
	**  Make sure the table or view exists.
	*/
	if not exists (select id
			from sysobjects
				where id = object_id(@tabname))
	begin
		/* 17492, "The table or view named doesn't exist in the current database." */
		exec sp_getmessage 17492, @msg out
		print @msg
		return (1)
	end

	/*
	**  See if any keys exist.
	*/
	if not exists (select *
			from syskeys
			where id = object_id(@tabname) or 
				depid = object_id(@tabname))
	begin
		/* 17660, "No defined keys for this object." */
		exec sp_getmessage 17660, @msg out
		print @msg
		return (1)
	end

	select @len1 = max(datalength(col_name(k.id, key1) + ", "
			+ isnull(col_name(k.id, key2), "*") + ", "
			+ isnull(col_name(k.id, key3), "*") + ", "
			+ isnull(col_name(k.id, key4), "*") + ", "
			+ isnull(col_name(k.id, key5), "*") + ", "
			+ isnull(col_name(k.id, key6), "*") + ", "
			+ isnull(col_name(k.id, key7), "*") + ", "
			+ isnull(col_name(k.id, key8), "*"))),
	       @len2 = max(datalength(
			  isnull(col_name(k.depid, depkey1), "*") + ", "
			+ isnull(col_name(k.depid, depkey2), "*") + ", "
			+ isnull(col_name(k.depid, depkey3), "*") + ", "
			+ isnull(col_name(k.depid, depkey4), "*") + ", "
			+ isnull(col_name(k.depid, depkey5), "*") + ", "
			+ isnull(col_name(k.depid, depkey6), "*") + ", "
			+ isnull(col_name(k.depid, depkey7), "*") + ", "
			+ isnull(col_name(k.depid, depkey8), "*")))
		from syskeys k
		    where k.id = object_id(@tabname) or 
			  k.depid = object_id(@tabname)

	if (@len1 > 70 or @len2 > 70)
	    select keytype = convert(char(10), v.name),
		object = object_name(k.id),
		related_object = isnull(object_name(k.depid), @none),
		object_keys = 	 col_name(k.id, key1) + ", "
			+ isnull(col_name(k.id, key2), "*") + ", "
			+ isnull(col_name(k.id, key3), "*") + ", "
			+ isnull(col_name(k.id, key4), "*") + ", "
			+ isnull(col_name(k.id, key5), "*") + ", "
			+ isnull(col_name(k.id, key6), "*") + ", "
			+ isnull(col_name(k.id, key7), "*") + ", "
			+ isnull(col_name(k.id, key8), "*"),
		related_keys =
			  isnull(col_name(k.depid, depkey1), "*") + ", "
			+ isnull(col_name(k.depid, depkey2), "*") + ", "
			+ isnull(col_name(k.depid, depkey3), "*") + ", "
			+ isnull(col_name(k.depid, depkey4), "*") + ", "
			+ isnull(col_name(k.depid, depkey5), "*") + ", "
			+ isnull(col_name(k.depid, depkey6), "*") + ", "
			+ isnull(col_name(k.depid, depkey7), "*") + ", "
			+ isnull(col_name(k.depid, depkey8), "*")
	    from syskeys k, master.dbo.spt_values v
		where k.type = v.number and v.type = 'K'
			and (k.id = object_id(@tabname) or 
			     k.depid = object_id(@tabname))
		order by object, keytype, related_object
	else
	    select keytype = convert(char(10), v.name),
		object = object_name(k.id),
		related_object = isnull(object_name(k.depid), @none),
		object_keys = convert(char(70),
				 col_name(k.id, key1) + ", "
			+ isnull(col_name(k.id, key2), "*") + ", "
			+ isnull(col_name(k.id, key3), "*") + ", "
			+ isnull(col_name(k.id, key4), "*") + ", "
			+ isnull(col_name(k.id, key5), "*") + ", "
			+ isnull(col_name(k.id, key6), "*") + ", "
			+ isnull(col_name(k.id, key7), "*") + ", "
			+ isnull(col_name(k.id, key8), "*")),
		related_keys = convert(char(70),
			  isnull(col_name(k.depid, depkey1), "*") + ", "
			+ isnull(col_name(k.depid, depkey2), "*") + ", "
			+ isnull(col_name(k.depid, depkey3), "*") + ", "
			+ isnull(col_name(k.depid, depkey4), "*") + ", "
			+ isnull(col_name(k.depid, depkey5), "*") + ", "
			+ isnull(col_name(k.depid, depkey6), "*") + ", "
			+ isnull(col_name(k.depid, depkey7), "*") + ", "
			+ isnull(col_name(k.depid, depkey8), "*"))
	    from syskeys k, master.dbo.spt_values v
		where k.type = v.number and v.type = 'K'
			and (k.id = object_id(@tabname) or 
			     k.depid = object_id(@tabname))
		order by object, keytype, related_object

	return (0)
end
go
exec sp_procxmode 'sp_helpkey', 'anymode'
go
grant execute on sp_helpkey to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_objectsegment')
begin
	drop procedure sp_objectsegment
end
go
print "Installing sp_objectsegment"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/lock */

/*
** Messages for "sp_objectsegment"      17714
**
** LOCALIZE the following:
**
**      select Data_located_on_segment = s.name, When_created = crdate
**
** Data_located_on_segment
** When_created
**
** 17714, "not applicable" 
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_objectsegment
@objname	varchar(92)	/* table name */
as
declare @msg varchar(30)


	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	/* 
	** Print out the create date for the object and it's
	** data segment, if applicable.
	*/

	/*
	**  Objects have the following value for sysstat & 7:
	**	0 - trigger
	**	1 - system table
	**	2 - view
	**	3 - user table
	**	4 - sproc
	**	5 - NOT UNUSED
	**	6 - default
	**	7 - rule
	*/
	if exists (select *
			from sysobjects
				where id = object_id(@objname)
					and sysstat & 7 in (1, 3))
	begin
		select Data_located_on_segment = s.name, When_created = crdate
			from sysobjects o, syssegments s, sysindexes i
				where o.id = object_id(@objname)
					and i.id = o.id
					and i.indid < 2
					and i.segment = s.segment
	end

	/*
	**  It's not a table so segment is not applicable.
	*/
	else
	begin
		/*
		** 17714, "not applicable" 
		*/
		exec sp_getmessage 17714, @msg output
		select Data_located_on_segment = @msg,
			When_created = crdate
		from sysobjects
			where id = object_id(@objname)
	end

return (0)

go
exec sp_procxmode 'sp_objectsegment', 'anymode'
go
grant execute on sp_objectsegment to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_indsuspect')
begin
	drop procedure sp_indsuspect
end
go
print "Installing sp_indsuspect"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages from sysmessages
**
** 17860, "Suspect indexes in database %1!:"
** 17861, "There are no suspect indexes in database %1!."
** 17862, "Table must be in the 'current' database."
** 17863, "There is no table named %1! in the 'current' database."
** 17864, "Suspect indexes on table %1!:"
** 17865, "There are no suspect indexes on table %1!."
*/

create procedure sp_indsuspect
@tab_name varchar(92) = NULL		/* if NULL, check all tables in db */
AS

declare @msg		varchar(255)	/* used for message to user */
declare @msg2		varchar(30)	/* used for table/db name */
declare @ind_suspect	smallint	/* value of IND_SUSPECT bit */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

/* 
** Specify the bit mask as -32768, not in hex notation, for portability
** to byte-swapped platforms.  This could break on a 1's complement 
** platform, but there isn't really a better solution.  SQL handles 
** hex numbers as binary data, not as numeric values as in C.
*/

select @ind_suspect = -32768

if (@tab_name is null)
begin
	/*
	** No table name specified, sp search for any
	** suspected indexes in the entire database.
	*/
	if exists (select * from sysindexes i
			where (i.status & @ind_suspect) != 0)
	begin
		/* 17860, "Suspect indexes in database %1!:" */
		exec sp_getmessage 17860, @msg output
		select @msg2 = db_name()
		print @msg, @msg2

		select
                        "Own.Tab.Ind (Obj_ID, Ind_ID)" =
				u.name + "." + o.name + '.' + i.name +
				' (' + convert(varchar, o.id) + ', ' +
				convert(varchar, i.indid) + ')'
		from
			sysobjects o,
			sysindexes i,
			sysusers u
		where
			o.id = i.id
		    and o.uid = u.uid
		    and (i.status & @ind_suspect) != 0
	end
	else
	begin
		/* 17861, "There are no suspect indexes in database %1!." */
		exec sp_getmessage 17861, @msg output
		select @msg2 = db_name()
		print @msg, @msg2
	end
end
else
begin
	/*
	** User has specified a table.
	** Check to see that the table name is local to the current database.
	*/
	if (@tab_name like '%.%.%')
	begin
		/* 17862, "Table must be in the 'current' database." */
		exec sp_getmessage 17862, @msg output
		print @msg
		return (1)
	end

	/*
	** Now, see if the table actually exists.
	*/
	if (object_id(@tab_name) is null)
	begin
		/* 17863, "There is no table named %1! in the 'current' database." */
		exec sp_getmessage 17863, @msg output
		print @msg, @tab_name
		return (2)
	end

	/*
	** Now, check for any suspect indexes on this table.
	*/
	if exists (select * from sysindexes i
			where i.id = object_id(@tab_name)
			  and (i.status & @ind_suspect) != 0)
	begin
		/* 17864, "Suspect indexes on table %1!:" */
		exec sp_getmessage 17864, @msg output
		print @msg, @tab_name

		select
                        "Own.Tab.Ind (Obj_ID, Ind_ID)" =
				u.name + "." + o.name + '.' + i.name +
				' (' + convert(varchar, o.id) + ', ' +
				convert(varchar, i.indid) + ')'
		from
			sysobjects o,
			sysindexes i,
			sysusers u
		where
			o.id = i.id
		    and o.uid = u.uid
		    and o.id = object_id(@tab_name)
		    and (i.status & @ind_suspect) != 0
	end
	else
	begin
		/* 17865, "There are no suspect indexes on table %1!." */
		exec sp_getmessage 17865, @msg output
		print @msg, @tab_name
	end
end
return (0)
go
exec sp_procxmode 'sp_indsuspect', 'anymode'
go
grant execute on sp_indsuspect to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpartition')
begin
	drop procedure sp_helpartition
end
go
print "Installing sp_helpartition"
go

/*
** Messages for "sp_helpartition"          18085
**
** 17460, "Object must be in the current database."
** 17461, "Object does not exist in this database."
** 18085, "Object is not partitioned."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_helpartition
@objname varchar(92)			/* the table to check for partitions */
as

declare @msg varchar(90)

if @@trancount = 0
begin
	set transaction isolation level 1
	set chained off
end

/*
**  Check to see that the object names are local to the current database.
*/
if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
begin
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return (1)
end

/*
**  Check to see the the table exists 
*/
if not exists (select id
		from sysobjects
			where id = object_id(@objname))
/*
**  Table doesn't exist so return.
*/
begin
	/* 17461, "Object does not exist in this database." */
	exec sp_getmessage 17461, @msg out
	print @msg
	return (1)
end

/*
**  If the table is not partitioned, return.
*/
if not exists (
	select * from syspartitions where id = object_id(@objname))
begin
	/* 18085, "Object is not partitioned." */
	exec sp_getmessage 18085, @msg out
	print @msg
	return (1)
end

/*
** Print partition information
*/
select	partitionid, firstpage, controlpage
from 	syspartitions 
where   id = object_id(@objname)

return (0)
go
exec sp_procxmode 'sp_helpartition', 'anymode'
go
grant execute on sp_helpartition to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_help')
begin
	drop procedure sp_help
end
go
print "Installing sp_help"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_help"               17570
**
** 17460, "Object must be in the current database."
** 17461, "Object does not exist in this database."
** 17570, "Operating System File"
** 17571, "---------------------"
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_help
@objname varchar(92) = NULL			/* object name we're after */
as

declare @typeid int				/* type of object in systypes */
declare @sysstat smallint			/* the type of the object */
declare @OS_file varchar(255)			/* physical file for ext tab */
declare @msg varchar(250)
declare @sptlang	int
declare @len1 int, @len2 int, @len3 int, @len4 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @sptlang = @@langid

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17100 and 17109
		and langid = @@langid)
	    select @sptlang = 0
end

set nocount on

/*
**  If no @objname given, give a little info about all objects.
**  Note: 0x80f is the mask for sysstats (=2063decimal).
** 	  800 is used by Stratus for external tables.
*/
if @objname is NULL
begin
	select @len1 = max(datalength(o.name)),
	       @len2 = max(datalength(user_name(uid)))
		from sysobjects o

	if (@len1 > 15 or @len2 > 15)
	    select Name = o.name,
		Owner = user_name(uid),
		Object_type = convert(char(22), m.description + x.name)

			from sysobjects o, master.dbo.spt_values v,
			master.dbo.spt_values x, master.dbo.sysmessages m
		where o.sysstat & 2063 = v.number
			and v.type = "O"
			and v.msgnum = m.error
			and isnull(m.langid, 0) = @sptlang
			and m.error between 17100 and 17109
			and x.type = "R"
			and o.userstat & -32768 = x.number
		order by Object_type desc, Name asc
	else
	    select Name = convert(char(15), o.name),
		Owner = convert(char(15), user_name(uid)),
		Object_type = convert(char(22), m.description + x.name)

			from sysobjects o, master.dbo.spt_values v,
			master.dbo.spt_values x, master.dbo.sysmessages m
		where o.sysstat & 2063 = v.number
			and v.type = "O"
			and v.msgnum = m.error
			and isnull(m.langid, 0) = @sptlang
			and m.error between 17100 and 17109
			and x.type = "R"
			and o.userstat & -32768 = x.number
		order by Object_type desc, Name asc


	select @len1 = max(datalength(s.name)),
	       @len2 = max(datalength(st.name)),
	       @len3 = max(datalength(object_name(s.tdefault))),
	       @len4 = max(datalength(object_name(s.domain)))
	from systypes s, systypes st
		where s.type = st.type
			and s.usertype > 99
			and st.usertype != 18 /* ignore sysname */
			and st.usertype < 100

	if (@len1 > 15 or @len2 > 15 or @len3 > 15 or @len4 > 15)
	    select User_type = s.name,
		Storage_type = st.name,
		Length = s.length,
		Nulls = s.allownulls,
		Default_name = object_name(s.tdefault),
		Rule_name = object_name(s.domain)
		from systypes s, systypes st
		    where s.type = st.type
			and s.usertype > 99
			and st.name not in ("sysname", "nchar", "nvarchar")
			and st.usertype < 100
		order by s.name
	else
	    select User_type = convert(char(15), s.name),
		Storage_type = convert(char(15), st.name),
		Length = s.length,
		Nulls = s.allownulls,
		Default_name = convert(char(15), object_name(s.tdefault)),
		Rule_name = convert(char(15), object_name(s.domain))
		from systypes s, systypes st
		    where s.type = st.type
			and s.usertype > 99
			and st.name not in ("sysname", "nchar", "nvarchar")
			and st.usertype < 100
		order by s.name

	return (0)
end

/*
**  Make sure the @objname is local to the current database.
*/
if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
begin
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return  (1)
end

/*
**  Now check to see if the @objname is in sysobjects.  It has to be either
**  in sysobjects or systypes.
*/
if not exists (select *
	from sysobjects
		where id = object_id(@objname))

/*
**  It wasn't in sysobjects so we'll check in systypes.
*/
begin
	select @typeid = usertype
		from systypes
			where name = @objname

	/*
	**  Time to give up -- @objname is not in sysobjects or systypes.
	*/
	if @typeid is NULL
	begin
		/* 17461, "Object does not exist in this database." */
		exec sp_getmessage 17461, @msg out
		print @msg
		return  (1)
	end

	/*
	** Print help about a data type
	*/
	select @len1 = max(datalength(s.name)),
	       @len2 = max(datalength(st.name)),
	       @len3 = max(datalength(object_name(s.tdefault))),
	       @len4 = max(datalength(object_name(s.domain)))
		from systypes s, systypes st
		    where s.usertype = @typeid
			and s.type = st.type
			and st.name not in ("sysname", "nchar", "nvarchar")
			and st.usertype < 100

	if (@len1 > 15 or @len2 > 15 or @len3 > 15 or @len4 > 15)
	    select Type_name = s.name,
		Storage_type = st.name,
		Length = s.length,

		Nulls = s.allownulls,
		Prec = s.prec,
		Scale = s.scale,
		Default_name = object_name(s.tdefault),
		Rule_name = object_name(s.domain),
		"Identity" = s.ident
		from systypes s, systypes st
		    where s.usertype = @typeid
			and s.type = st.type
			and st.name not in ("sysname", "nchar", "nvarchar")
			and st.usertype < 100
	else
	    select Type_name = convert(char(15), s.name),
		Storage_type = convert(char(15), st.name),
		Length = s.length,

		Prec = s.prec,
		Scale = s.scale,
		Nulls = s.allownulls,
		Default_name = convert(char(15), object_name(s.tdefault)),
		Rule_name = convert(char(15), object_name(s.domain)),
		"Identity" = s.ident
		from systypes s, systypes st
		    where s.usertype = @typeid
			and s.type = st.type
			and st.name not in ("sysname", "nchar", "nvarchar")
			and st.usertype < 100

	return (0)
end

/*
**  It's in sysobjects so print out the information.
*/
select Name = o.name, Owner = user_name(uid), 
	Type = convert(char(22), m.description + x.name)

	from sysobjects o, master.dbo.spt_values v,
		master.dbo.spt_values x, master.dbo.sysmessages m
	where o.id = object_id(@objname)
		and o.sysstat & 2063 = v.number
		and v.type = "O"
		and v.msgnum = m.error
		and isnull(m.langid, 0) = @sptlang
		and m.error between 17100 and 17199
		and x.type = "R"
		and o.userstat & -32768 = x.number

execute sp_objectsegment @objname

/*
**  Objects have the following value for sysstat & 15:
**	0 - trigger
**	1 - system table
**	2 - view
**	3 - user table
**	4 - sproc
**	5 - log
**	6 - default
**	7 - rule
**	8 - trigger
**	9 - referential constraint
**	10 - check constraint
**	
**
**  If the object is a system table, view, or user table, we want to check
**  out the objects columns here.
*/

select @sysstat = sysstat
	from sysobjects
		where id = object_id(@objname)

/*
**  Fix of bug 91669:
**  For the current design, a view having nameless column may be created,
**  e.g. create view view1 as select sum(column1) from table1. 
**  In this case, c.name is NULL. Using builtin function isnull() to  
**  make the following query work. 
*/

if @sysstat & 15 in (1, 2, 3)
begin
	select Column_name = isnull(c.name, 'NULL'),
	       Type = t.name,
	       Length = c.length,
	       Prec = c.prec,
	       Scale = c.scale,
	       Nulls = convert(bit, (c.status & 8)),
	       Default_name = object_name(c.cdefault),
	       Rule_name = object_name(c.domain),
	       rtype = t.type, utype = t.usertype,
	       Ident = convert(bit, (c.status & 0x80))
	into #helptype
	from syscolumns c, systypes t
		where c.id = object_id(@objname)
			and c.usertype *= t.usertype

	/* Handle National Characters */
	update #helptype
		set Length = Length / @@ncharsize
		where (rtype = 47 and utype = 24)
		   or (rtype = 39 and utype = 25)

	select @len1 = max(datalength(Column_name)),
	       @len2 = max(datalength(Type)),
	       @len3 = max(datalength(Default_name)),
	       @len4 = max(datalength(Rule_name))
	from #helptype

	if (@len1 > 15 or @len2 > 15 or @len3 > 15 or @len4 > 15)
	    select Column_name,
		   Type,
		   Length,
		   Prec,
		   Scale,
		   Nulls,
		   Default_name,
		   Rule_name,
		   "Identity" = Ident
		from #helptype
	else
	    select Column_name = convert(char(15), Column_name),
		   Type = convert(char(15), Type),
		   Length,
		   Prec,
		   Scale,
		   Nulls,
		   Default_name = convert(char(15), Default_name),
		   Rule_name = convert(char(15), Rule_name),
		   "Identity" = Ident
		from #helptype

	drop table #helptype
end

/*
**  For procedures, the parameters of the procedures are stored in syscolumns.
*/
if @sysstat & 15 = 4
begin
	/*
	**  Does the sproc have any parameters?
	*/
	if exists (select *
			from syscolumns c, systypes t
				where c.id = object_id(@objname)
					and c.usertype *= t.usertype)
	begin
		select Parameter_name = convert(char(15), c.name),
		       Type = convert(char(15), t.name),
		       Length = c.length,
		       Prec = c.prec,
		       Scale = c.scale,
		       Param_order=c.colid,
		       rtype = t.type, utype = t.usertype
		into #helpproc
		from syscolumns c, systypes t
			where c.id = object_id(@objname)
				and c.usertype *= t.usertype

		/* Handle National Characters */
		update #helpproc
			set Length = Length / @@ncharsize
			where (rtype = 47 and utype = 24)
			   or (rtype = 39 and utype = 25)

		select @len1 = max(datalength(Parameter_name)),
		       @len2 = max(datalength(Type))
		from #helpproc

		if (@len1 > 15 or @len2 > 15)
		    select Parameter_name,
			   Type,
			   Length,
			   Prec,
			   Scale,
			   Param_order
		    from #helpproc
		else
		    select Parameter_name = convert(char(15), Parameter_name),
			   Type = convert(char(15), Type),
			   Length,
			   Prec,
			   Scale,
			   Param_order
		    from #helpproc

		drop table #helpproc
	end
end

/*
**  If the object is an external table, show which OS file it's using.
*/
if @sysstat & 2063 = 2051
begin
	select @OS_file = name from sysindexes
		where id = object_id(@objname)
		and indid in (0,1)
	/*
	** 17570, "Operating System File"
	** 17571, "---------------------"
	*/
	print ""
	exec sp_getmessage 17570, @msg out
	print @msg
	exec sp_getmessage 17571, @msg out
	print @msg
	print @OS_file
	print ""
end

/* 
**  If the object is a table, display sysattributes information
**  if there is any.  It could be in the current database under
**  type "T".
*/

if @sysstat & 15 in (1, 3)
begin
	/*  Create temporary table for sysattributes data */
	create table #sphelpattr
	(
		class 		varchar(30),
		attribute 	varchar(30),
		int_value	int NULL,
		char_value	varchar(255) NULL,
		comments	varchar(255) NULL
	)

	/* 
	**  The join with master..sysattributes here is to
	**  get the string descriptions for the class and attribute.
	**  These should never be more than 30 chars, so it's okay to
	**  truncate them.
	*/

	insert #sphelpattr (class, attribute, int_value, char_value, comments)
		select convert(char(30),c.char_value), 
			convert(char(30),a.char_value),
			t.int_value, t.char_value, t.comments
		from sysattributes t, master.dbo.sysattributes c, 
			master.dbo.sysattributes a
		where t.object_type = "T"
		and t.object = object_id(@objname)
		and c.class = 0 and c.attribute = 0
		and a.class = 0 and a.attribute = 1
		and t.class = c.object
		and t.class = a.object
		and t.attribute = a.object_info1
	
	if exists (select * from #sphelpattr)
	begin
		select attribute_class = class, attribute, int_value,
			char_value, comments
		from #sphelpattr
	end
	drop table #sphelpattr
end

/* 
**  If the object is a procedure, display sysattributes information
**  if there is any.
*/

if @sysstat & 15 = 4
begin
	if exists (select * from sysattributes
			where  object_type = "P"
			and object = object_id(@objname))
	begin
		/* 
		**  The join with master..sysattributes here is to
		**  get the string descriptions for the class 
		**  (master.dbo.sysattributes c) and attribute
		**  (master.dbo.sysattributes a).
		*/

		select  attribute_class = convert(char(30),c.char_value), 
			attribute = convert(char(30),a.char_value),
			t.int_value, t.char_value, t.comments
		from sysattributes t, master.dbo.sysattributes c, 
			master.dbo.sysattributes a
		where t.object_type = "P"
		and t.object = object_id(@objname)
		and c.class = 0 and c.attribute = 0
		and a.class = 0 and a.attribute = 1
		and t.class = c.object
		and t.class = a.object
		and t.attribute = a.object_info1
	end
end

/*
**  If the object is a table, check out the indexes.
*/
if @sysstat & 15 in (1, 3)
	execute dbo.sp_helpindex @objname

/*
**  If the object is a table or view, check out the keys.
*/
if @sysstat & 15 in (1, 2, 3)
	execute dbo.sp_helpkey @objname

/*
**  If the object is a table, check out the slices/partitions
*/
if @sysstat & 15 in (1, 3)
	execute dbo.sp_helpartition @objname

return (0)
go
exec sp_procxmode 'sp_help', 'anymode'
go
grant execute on sp_help to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helprotect')
begin
	drop procedure sp_helprotect
end
go
print "Installing sp_helprotect"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/help */
/*
** Messages for "sp_helprotect"         17673
**
** 17431, "true"
** 17432, "false"
** 17460, "Object must be in the current database."
** 17232, "No user with the specified name exists in the current database."
** 17673, "All"
** 17674, "No such object or user exists in the database."
** 17675, "Illegal string found where the keyword grant is expected."
** 17676, "This may be a temporary object. Please execute procedure from tempdb."
*/
create procedure sp_helprotect
@name varchar(92) = NULL,	/* name of object or user to check	*/
@username varchar(30) = NULL,	/* name of user to restrict check	*/
@option varchar(10) = NULL /* keyword grant implies with grant option	*/
as

declare @low int			/* range of userids to check */
declare @high int
declare @olow int			/* range of objectids to check */
declare @ohigh int
declare @objid int			/* id of @name if object */
declare @msg	varchar(100)
declare @msg_true varchar(9)		/* msg for "true" equivalent */
declare @msg_false varchar(9)		/* msg for "false" equivalent */
declare @len1 int, @len2 int
declare @len3 int, @len4 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see that the object names are local to the current database.
*/
if @name like "%.%.%" and
	substring(@name, 1, charindex(".", @name) - 1) != db_name()
begin
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return (1)
end

/*  If this is a temporary table; object does not belong to 
**  this database; (we should be in the tempdb)
*/
if (@name like "#%" and db_name() != "tempdb")
begin
	/* 
	** 17676, "This may be a temporary object. Please execute 
	** procedure from tempdb."
	*/
	exec sp_getmessage 17676, @msg out
	print @msg
	return (1)
end

/*
** Check if the grant keyword is correct
*/
if lower(@option) != "grant"
begin
	/*
	** 17675, "Illegal string found where the keyword grant is expected."
	*/
	exec sp_getmessage 17675, @msg output
	print @msg
	return (1)
end

/*
**  Initialize the range of user ids to check.  We will either check all
**  users (the initial values) or just one in particular (@low = @high)
**  NOTE: @low has been set to -16384 because uid's currently range  
**  from -16383 to +16383. So no uid can take the value of -16384.
**  However, if the datatype of uid's is changed in the future,
**  OR if the range of uids is extended (as it would be in 11.9.5 where 
**  the uid range would stretch from -32K to +16K), this value would have 
**  to be modified appropriately.
*/
select @low = -16384, @high = 32767
select @olow = -1, @ohigh = 2147483647


/*
**  There are two cases handled by this procedure.  If the first parameter
**  is an object (table, view, procedure) then @name is taken as an object
**  name and the procedure will figure out permissions for the object.
**
**  If the first parameter is not one of the objects mentioned it will be
**  taken as user name and all the permissions for the user or group name
**  will be shown.
*/

if @name is not NULL
begin
	/*
	**  Check to see if it's an object.
	*/
	if exists (select *
			from sysobjects
				where id = object_id(@name)
					and (sysstat & 15 = 1	/* system table */
					or sysstat & 15 = 2	/* view */
					or sysstat & 15 = 3	/* user table */
					or sysstat & 15 = 4))	/* procedure */
	begin
		/*
		**  Set @olow and @ohigh so the search will be restricted to
		**  a particular object.
		*/
		select @olow = id, @ohigh = id
			from sysobjects
				where id = object_id(@name)
	end
	else
	begin
		/*
		**  Since @name is not an object let's try it as a user.
		*/

		/*
		**  Set @low and @high so the search will be restricted to
		**  a particular user.
		*/
		select @low = uid, @high = uid
			from sysusers
				where name = @name

		/*
		**  @name isn't a user either so return.
		*/
		if @low = -16384
		begin
			/* 
			** 17674, "No such object or user exists in the database."
			*/
			exec sp_getmessage 17674, @msg out
			print @msg
			return (1)
		end
	end
end

if @username is not NULL
begin
	/* Re-initialize @low to validate @username */
	select @low = -16384

	select @low = uid
		from sysusers
			where name = @username

	/*
	**  @username isn't valid.
	*/
	if @low = -16384
	begin
		/* 17232, "No user with the specified name exists in the current database." */
		exec sp_getmessage 17232, @msg out
		print @msg
		return (1)
	end
	else 
	begin
		/*
		** If we already have a userid in @high, then they
		** specified a user in @name as well.  The two
		** had better be the same.
		*/
		if @high != 32767 
		begin
			if @low != @high
 			begin
				/* 
				** 17677, "sp_helprotect [name [, name_in_db [, "grant"]]]"
				*/
				exec sp_getmessage 17677, @msg out
				print @msg
				return (1)
			end 	
		end
		else 
		begin
			select @high = @low
		end
	end
end

set nocount on

create table #sysprotects1 (id int, uid smallint, action tinyint,
	protecttype tinyint, grantor smallint, number int)

create table #sysprotects2 (id int, col_count int)

insert into #sysprotects2 (id, col_count)
	select id, count (*)
	from syscolumns
	group by id

insert into #sysprotects1 (id, uid, action, protecttype,
	grantor, number)
	select distinct
		p.id, p.uid, p.action, p.protecttype,
		p.grantor, c.number
		from sysprotects p, master.dbo.spt_values c
		where (~isnull (convert(tinyint, substring(p.columns, c.low, 1)), 0) & c.high != 0
			and c.number <= (select col_count from #sysprotects2 where id = p.id))
			and c.type = "P"
			and c.number <= 255
			and p.columns is not null
			and convert(tinyint, substring(p.columns, 1, 1)) & 0x1 != 0
			and (convert(tinyint, substring(p.columns, 1, 1)) & 0xfe != 0
				or substring(p.columns, 2, 1) is not null)
			and p.id between @olow and @ohigh
			and p.uid between @low and @high

insert into #sysprotects1 (id, uid, action, protecttype,
	grantor, number)
	select distinct
		p.id, p.uid, p.action, p.protecttype,
		p.grantor, c.number
		from sysprotects p, master.dbo.spt_values c
		where convert(tinyint, substring(isnull(p.columns, 0x1), c.low, 1))
			& c.high != 0
			and c.type = "P"
			and c.number <= 255
			and (p.columns is null
				or convert(tinyint, substring(p.columns, 1, 1)) & 0x1 = 0
				or (convert(tinyint, substring(p.columns, 1, 1)) & 0xfe = 0
					and substring(p.columns, 2, 1) is null))
			and p.id between @olow and @ohigh
			and p.uid between @low and @high

/*
** 17431, "true"
** 17432, "false"
*/
exec sp_getmessage 17431, @msg_true output
exec sp_getmessage 17432, @msg_false output

/* 17673, "All" */
exec sp_getmessage 17673, @msg out

if @option is NULL
begin
	/*
	** print all the privileges
	*/

	/* First get the max length of char columns for display. */
	select
		@len1 = max(datalength(user_name(p.grantor))),
		@len2 = max(datalength(user_name(p.uid))),
		@len3 = max(datalength(isnull(object_name(p.id), ""))),
		@len4 = max(datalength(isnull(col_name(id, p.number), @msg)))
			from #sysprotects1 p, master.dbo.spt_values a,
				master.dbo.spt_values b
			where a.type = "T"
				and a.number = p.action
				and b.type = "T"
				and (b.number = (p.protecttype + 204)
				     or (b.number = (p.protecttype + 205)
					 and p.protecttype = 0))
				and p.id between @olow and @ohigh
				and p.uid between @low and @high

	if (@len1 > 15 or @len2 > 15 or @len3 > 15 or @len4 > 10)
	begin
	    select distinct
		grantor = user_name(p.grantor),
		grantee = user_name(p.uid),
		type = substring(b.name, 1, 8),
		action = a.name,
		object = isnull(object_name(p.id), ""),
		column = isnull(col_name(id, p.number), @msg),
		grantable = upper(@msg_false)
			from #sysprotects1 p, master.dbo.spt_values a,
				master.dbo.spt_values b
			where a.type = "T"
				and a.number = p.action
				and b.type = "T"
				and b.number = (p.protecttype + 204)
				and p.id between @olow and @ohigh
				and p.uid between @low and @high

	    union

	    select distinct
			grantor = user_name(p.grantor),
			grantee = user_name(p.uid),
			type = substring(b.name, 1, 8),
			action = a.name,
			object = isnull(object_name(p.id), ""),
			column = isnull(col_name(id, p.number), @msg),
			grantable = upper(@msg_true)
			from #sysprotects1 p, master.dbo.spt_values a,
				master.dbo.spt_values b
			where a.type = "T"
				and a.number = p.action
				and b.type = "T"
				and b.number = (p.protecttype + 205)
				and p.protecttype = 0
				and p.id between @olow and @ohigh
				and p.uid between @low and @high

		order by grantor, grantee, type, action, object, column
	end
	else
	begin
	    select distinct
		grantor = substring(user_name(p.grantor), 1, 15),
		grantee = substring(user_name(p.uid), 1, 15),
		type = substring(b.name, 1, 8),
		action = a.name,
		object = substring(isnull(object_name(p.id), ""), 1, 15),
		column = substring(isnull(col_name(id, p.number), @msg), 1, 10),
		grantable = upper(@msg_false)
			from #sysprotects1 p, master.dbo.spt_values a,
				master.dbo.spt_values b
			where a.type = "T"
				and a.number = p.action
				and b.type = "T"
				and b.number = (p.protecttype + 204)
				and p.id between @olow and @ohigh
				and p.uid between @low and @high

	    union

	    select distinct
			grantor = substring(user_name(p.grantor), 1, 15),
			grantee = substring(user_name(p.uid), 1, 15),
			type = substring(b.name, 1, 8),
			action = a.name,
			object = substring(isnull(object_name(p.id), ""), 1, 15),
			column = substring(isnull(col_name(id, p.number), @msg), 1, 10),
			grantable = upper(@msg_true)
			from #sysprotects1 p, master.dbo.spt_values a,
				master.dbo.spt_values b
			where a.type = "T"
				and a.number = p.action
				and b.type = "T"
				and b.number = (p.protecttype + 205)
				and p.protecttype = 0
				and p.id between @olow and @ohigh
				and p.uid between @low and @high

		order by grantor, grantee, type, action, object, column
	end
end
else
begin

	/*
	** print only the grantable privileges
	*/

	/* Get the max length of the char columns for display */
	select
		@len1 = max(datalength(user_name(p.grantor))),
		@len2 = max(datalength(user_name(p.uid))),
		@len3 = max(datalength(isnull(object_name(p.id), ""))),
		@len4 = max(datalength(isnull(col_name(id, p.number), @msg)))
		from #sysprotects1 p, master.dbo.spt_values a,
			master.dbo.spt_values b
		where a.type = "T"
			and a.number = p.action
			and b.type = "T"
			and b.number = (p.protecttype + 205)
			and p.protecttype = 0
			and p.id between @olow and @ohigh
			and p.uid between @low and @high

	if (@len1 > 15 or @len2 > 15 or @len3 > 15 or @len4 > 10)
		select distinct
			grantor = user_name(p.grantor),
			grantee = user_name(p.uid),
			type = substring(b.name, 1, 8),
			action = a.name,
			object = isnull(object_name(p.id), ""),
			column = isnull(col_name(id, p.number), @msg),
			grantable = upper(@msg_true)
			from #sysprotects1 p, master.dbo.spt_values a,
				master.dbo.spt_values b
			where a.type = "T"
				and a.number = p.action
				and b.type = "T"
				and b.number = (p.protecttype + 205)
				and p.protecttype = 0
				and p.id between @olow and @ohigh
				and p.uid between @low and @high
			order by grantor, grantee, type, action, object, column
	else
		select distinct
			grantor = substring(user_name(p.grantor), 1, 15),
			grantee = substring(user_name(p.uid), 1, 15),
			type = substring(b.name, 1, 8),
			action = a.name,
			object = substring(isnull(object_name(p.id), ""), 1, 15),
			column = substring(isnull(col_name(id, p.number), @msg), 1, 10),
			grantable = upper(@msg_true)
			from #sysprotects1 p, master.dbo.spt_values a,
				master.dbo.spt_values b
			where a.type = "T"
				and a.number = p.action
				and b.type = "T"
				and b.number = (p.protecttype + 205)
				and p.protecttype = 0
				and p.id between @olow and @ohigh
				and p.uid between @low and @high
			order by grantor, grantee, type, action, object, column
end
return (0)
go
exec sp_procxmode 'sp_helprotect', 'anymode'
go
grant execute on sp_helprotect to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helptext')
begin
	drop procedure sp_helptext
end
go
print "Installing sp_helptext"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/helptext */
/*
** Messages for "sp_helptext"           17nnn
**
** 17460, "Object must be in the current database."
** 17461, "Object does not exist in this database." 
** 17679, "There is no text for object @objname." 
*/
create procedure sp_helptext
@objname varchar(92)
as
declare @text_count int
declare @msg varchar(100)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Make sure the @objname is local to the current database.
*/
if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
begin
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return (1)
end

/*
**  See if @objname exists.
*/
if (object_id(@objname) is NULL)
begin
	/* 17461, "Object does not exist in this database." */
	exec sp_getmessage 17461, @msg out
	print @msg
	return (1)
end

/*
**  Find out howmany lines of text are coming back.
**	and return if there are none.
*/
select @text_count = count(*)
	from syscomments
where id = object_id(@objname)

if @text_count = 0
begin
	/* 17679, "There is no text for object @objname." */
	exec sp_getmessage 17679, @msg out
	print @msg, @objname
	return (1)
end
	
/*
**  Return # howmany lines of text that are about to come back.
**  This is required by the "old" report writer.
*/
select "# Lines of Text" = @text_count

/*
**  Now get the text.
*/
select text
	from syscomments 
where id = object_id(@objname)
		order by number, colid2, colid

return (0)
go
exec sp_procxmode 'sp_helptext', 'anymode'
go
grant execute on sp_helptext to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpthreshold')
begin
	drop procedure sp_helpthreshold
end
go
print "Installing sp_helpthreshold"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_helpthreshold"     17910
**
** 17910, "Database '%1!' has no thresholds -- table '%2!' does not exist."
** 17911, "Segment '%1!' does not exist."
*/

create procedure sp_helpthreshold
@segname	varchar(30)=NULL
as

declare	@msg	varchar(255),
	@dbname	varchar(30)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
** Make sure our database is recent enough to contain Systhresholds
*/
if (select name from sysobjects
	where	name = 'systhresholds'
	  and	type = 'S')
   is NULL
begin
	/*
	** 17910, "Database '%1!' has no thresholds -- table '%2!' does not
	**	  exist."
	*/
	exec sp_getmessage 17910, @msg output
	select @dbname = db_name()
	print @msg, @dbname, "systhresholds" 
	return (1)
end

/*
** If user wants a specific segment's thresholds, show those.
*/
if (@segname is not NULL)
begin
	if (select segment from syssegments where name = @segname) is NULL
	begin
		/*
		** 17911, "Segment '%1!' does not exist."
		*/
		exec sp_getmessage 17911, @msg output
		print @msg, @segname
		return (2)
	end

	select	"segment name"=s.name,
		"free pages"=t.free_space,
		"last chance?"=t.status,
		"threshold procedure"=t.proc_name
	from syssegments s, systhresholds t
	where s.segment = t.segment
	  and s.name = @segname

	return (0)
end

/*
** Show all thresholds
*/
select	"segment name"=s.name,
	"free pages"=t.free_space,
	"last chance?"=t.status,
	"threshold procedure"=t.proc_name
from syssegments s, systhresholds t
where s.segment = t.segment

return (0)
go
exec sp_procxmode 'sp_helpthreshold', 'anymode'
go
grant execute on sp_helpthreshold to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_lock')
begin
	drop procedure sp_lock
end
go
print "Installing sp_lock"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/lock */
/*
** Messages for "sp_lock"
**
** 18052, "The class column will display the cursor name for locks associated
**         with a cursor for the current user and the cursor id for other 
**         users."
*/


create procedure sp_lock
@spid1 int = NULL,		/* server process id to check for locks */
@spid2 int = NULL		/* other process id to check for locks */
as

declare @length int
declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*  Print warning message about cursor lock info:
**  18052, "The class column will display the cursor name for locks associated
**          with a cursor for the current user and the cursor id for other 
**          users."
*/
exec sp_getmessage 18052, @msg out
print @msg

/*
**  Show the locks for both parameters.
*/
if @spid1 is not NULL
begin
    select @length = max(datalength(db_name(dbid)))
	from master..syslocks
		where spid in (@spid1, @spid2)

    if (@length > 15)
	select spid, locktype = name, table_id = id, page,
		dbname = db_name(dbid), class
	from master..syslocks l, master..spt_values v
		where l.type = v.number
			and v.type = "L"
			and spid in (@spid1, @spid2)
    else
	select spid, locktype = name, table_id = id, page,
		dbname = convert(char(15), db_name(dbid)), class
	from master..syslocks l, master..spt_values v
		where l.type = v.number
			and v.type = "L"
			and spid in (@spid1, @spid2)
end

/*
**  No parameters, so show all the locks.
*/
else
begin
    select @length = max(datalength(db_name(dbid)))
	from master..syslocks

    if (@length > 15)
	select spid, locktype = name, table_id = id, page,
		dbname = db_name(dbid), class
	from master..syslocks l, master..spt_values v
		where l.type = v.number
			and v.type = "L"
	order by spid, dbname, table_id, locktype, page
    else
	select spid, locktype = name, table_id = id, page,
		dbname = convert(char(15), db_name(dbid)), class
	from master..syslocks l, master..spt_values v
		where l.type = v.number
			and v.type = "L"
	order by spid, dbname, table_id, locktype, page
end

return (0)
go
exec sp_procxmode 'sp_lock', 'anymode'
go
grant execute on sp_lock to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_logdevice')
begin
	drop procedure sp_logdevice
end
go
print "Installing sp_logdevice"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	5.0	14.2	11/12/91	sproc/src/logdevice */

/*
** Messages for "sp_logdevice"          17710
**
** 17260, "Can't run %1! from within a transaction."
** 17421, "No such database -- run sp_helpdb to list databases."
** 17471, "No such device exists -- run sp_helpdevice to list the DataServer devices."
** 17281, "The specified device is not used by the database."
** 17710, "This command has been ignored.  The device specified
**	   is the only non-log device available for the database and
**	   cannot be made log-only."
** 17711, "Syslogs moved."
** 17715, "The last-chance threshold for database %1! is now %2! pages."
** 17716, "Could not update the last-chance threshold for database %1!"
** 17289, "Set your curwrite to the hurdle of current database."
*/

create procedure sp_logdevice
@dbname	varchar(30),		/* database name that has the syslogs */
@devname	varchar(30)	/* device name to put syslogs on */
as

declare @dbid	smallint	/* dbid of the database to be changed */
declare @dbuid	smallint	/* id of the owner of the database */
declare @logbit	int		/* this is the bit to turn on in sysusages */
declare @lct	int		/* last-chance threshold value */
declare @msg    varchar(250)



/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_logdevice"
        return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

select @logbit = 4		/* bit 3 is the one to turn on */

/*
**  Verify the database name and get the @dbid and @dbuid
*/
select @dbid = dbid, @dbuid = suid
	from master.dbo.sysdatabases
		where name = @dbname

/*
**  If @dbname not found, say so and list the databases.
*/
if @dbid is NULL
begin
	/*
	** 17421, "No such database -- run sp_helpdb to list databases."
	*/
	exec sp_getmessage 17421, @msg output
	print @msg
	return (1)
end

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA authorization can execute it.
**  Call proc_role() with the required SA authorization.
*/
if ((suser_id() != @dbuid) and (proc_role("sa_role") != 1))
	return(1)

/*
**  See if the device exists.
*/
if not exists (select *
		from master.dbo.sysdevices
			where name like @devname)
begin
	/*
	** 17471, "No such device exists -- run sp_helpdevice to list the DataServer devices."
	*/
	exec sp_getmessage 17471, @msg output
	print @msg
	return (1)
end

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if ((suser_id() != @dbuid) and (proc_role("sa_role") != 1))
	return(1)

/*
**  Now see if the @dbname uses the @devname
*/
if not exists (select *
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = @dbid)
begin
	/*
	** 17281, "The specified device is not used by the database."
	*/
	exec sp_getmessage 17281, @msg output
	print @msg
	return (1)
end

/*
**  Check if there are any additional segments on original device to be made
**  into log only (don't want to make the only segment not usable for data!)
*/
if (select count(*)
	from master.dbo.sysusages u, master.dbo.sysdevices d
		where d.name != @devname
			and u.vstart between d.low and d.high
			and u.dbid = @dbid
			and u.segmap != @logbit
			and d.cntrltype = 0) = 0
begin
	/*
	** 17710, "This command has been ignored.  The device specified
	** is the only non-log device available for the database and
	** cannot be made log-only."
	*/
	exec sp_getmessage 17710, @msg output
	print @msg
	return (1)
end

/*
**  Set the segments on @devname as log-only.
*/
begin transaction

update master.dbo.sysusages
	set segmap = @logbit
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where d.name = @devname
				and u.vstart between d.low and d.high
				and u.dbid = @dbid

/*
**  Clear the bit from any database segments on other devices that aren't
**  already log only.
*/
update master.dbo.sysusages
	set segmap = segmap & ~@logbit
		from master.dbo.sysusages u, master.dbo.sysdevices d
			where u.dbid = @dbid
			and u.vstart between d.low and d.high
			and d.name != @devname
			and u.segmap != @logbit

if @@rowcount = 0
	rollback transaction
else
	commit transaction

/*
**  Now we need to activate the new segment map.
*/
dbcc dbrepair (@dbname, remap)

/*
** We might be extending onto a segment that used to contain user data,
** so we need to look for stranded objects.
*/
dbcc dbrepair (@dbname, findstranded)

/*
** Recalculate the last-chance threshold
*/
select @lct = lct_admin("lastchance", @dbid)

/*
** 17711, "Syslogs moved."
*/
exec sp_getmessage 17711, @msg output
print @msg

/*
** Show what the last-chance threshold changed to
*/
if (@lct > 0)
	exec sp_getmessage 17715, @msg output
else
	exec sp_getmessage 17716, @msg output
print @msg, @dbname, @lct

return (0)
go
exec sp_procxmode 'sp_logdevice', 'anymode'
go
grant execute on sp_logdevice to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_lookup')
begin
	drop procedure sp_lookup
end
go
print "Installing sp_lookup"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/lock */

create procedure sp_lookup
@typearg int,
@owname	varchar(30) = "%", /* owner of the desired objects (except indexes) */
@obname	varchar(30) = "%", /* name of the desired objects (including indexes) */
@indtab	varchar(30) = "%", /* table associated with the desired index */
@indown varchar(30) = "%"  /* owner of the desired index */
as
	create table #ddtab
		(name	varchar(30),
		 owner	varchar(30),
		 type	int,
		 indtab	varchar(30))

declare @table	int
declare @view	int
declare @index	int
declare @sproc	int
declare @trgr	int
declare @dflt	int
declare @rule	int
declare @dtype	int
declare @db	int
declare @report int



if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @table = 1, @view = 2, @index = 4, @sproc = 8, @trgr = 16, @dflt = 32,
	@rule = 64, @dtype = 128, @db = 256, @report = 512

if (@typearg & @table = @table)
	insert into #ddtab
		select name, user_name(uid), @table, '' from dbo.sysobjects
			where name like @obname
				and user_name(uid) like @owname
				and (sysstat & 7 = 1	/* system table */
		  		or sysstat & 7 = 3)	/* user table */


if (@typearg & @view = @view)
	insert into #ddtab
		select name, user_name(uid), @view, '' from dbo.sysobjects
			where name like @obname
				and user_name(uid) like @owname
			  	and sysstat & 7 = 2		/* view */

if (@typearg & @index = @index)
	insert into #ddtab
		select i.name, user_name(o.uid), @index, o.name
			from dbo.sysindexes i, dbo.sysobjects o
				where i.name like @obname
					and i.indid > 0
					and i.id = o.id
					and user_name(o.uid) like @indown
					and o.name = object_name(o.id)
					and o.name like @indtab

if (@typearg & @report = @report)
	insert into #ddtab
		select name, user_name(uid), @report, '' from dbo.sysobjects
			where name like @obname
				and user_name(uid) like @owname
				and sysstat & 7 = 4		/* sproc */
				and userstat & -32768 = -32768	/* report */

if (@typearg & @sproc = @sproc)
begin
	/*
	**  If we also wanted reports, don't pick up reports again as sprocs.
	*/
	if (@typearg & @report = @report)
	begin
		insert into #ddtab
			select name, user_name(uid), @sproc, '' from dbo.sysobjects
			 where name like @obname
				and user_name(uid) like @owname
				and sysstat & 7 = 4	/* stored procedure */
				and userstat & -32768 != -32768	/* report */
	end
	else
	begin
		insert into #ddtab
			select name, user_name(uid), @sproc, '' from dbo.sysobjects
			 where name like @obname
				and user_name(uid) like @owname
				and sysstat & 7 = 4	/* stored procedure */
	end
end

if (@typearg & @trgr = @trgr)
	insert into #ddtab
		select name, user_name(uid), @trgr, '' from dbo.sysobjects
			where name like @obname
				and user_name(uid) like @owname
			  	and sysstat & 7 = 0	/* trigger */

if (@typearg & @dflt = @dflt)
	insert into #ddtab
		select name, user_name(uid), @dflt, '' from dbo.sysobjects
			 where name like @obname
			 	and user_name(uid) like @owname
			 	and sysstat & 7 = 6		/* default */

if (@typearg & @rule = @rule)
	insert into #ddtab
		select name, user_name(uid), @rule, '' from dbo.sysobjects
			 where name like @obname
			 	and user_name(uid) like @owname
			 	and sysstat & 7 = 7		/* rule */

if (@typearg & @dtype = @dtype)
	insert into #ddtab
		select name, user_name(uid), @dtype, '' from dbo.systypes
			where name like @obname
				and user_name(uid) like @owname

if (@typearg & @db = @db)
	insert into #ddtab
		select name, suser_name(suid), @db, ''
			from master.dbo.sysdatabases
				where (name like @obname)
					and suser_name(suid) like @owname

select * from #ddtab order by name

drop table #ddtab

return (0)
go
exec sp_procxmode 'sp_lookup', 'anymode'
go
grant execute on sp_lookup to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpremotelogin')
begin
	drop procedure sp_helpremotelogin
end
go
print "Installing sp_helpremotelogin"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */
/*
** Messages for "sp_helpremotelogin"    17680
**
** 17680, "There are no remote servers defined."
** 17681, "There are no remote logins for the remote server '%1!'."
** 17682, "There are no remotelogins defined."
** 17683, "There are no remote logins for '%1!'."
** 17684, "There are no remote logins."
** 17685, "There are no remote logins for '%1!' on remote server '%2!'."
** 17686, "** mapped locally **"
** 17687, "** use local name **"
** 17661, "-- none --"
*/
create procedure sp_helpremotelogin
@remoteserver varchar(30) = NULL,	/* remote server name */
@remotename varchar(30) = NULL		/* remote login name */
as

declare	@msg	varchar(100)
declare @sptlang	int
declare @len1 int, @len2 int, @len3 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

/*
**  If no server given, get 'em all.
*/
if @remoteserver is null
begin
	select @remoteserver = "%"
end

else
begin
	if not exists (select *
			from master.dbo.sysservers s,
				master.dbo.sysremotelogins r
			where s.srvid = r.remoteserverid
				and s.srvname like @remoteserver
				and s.srvid > 0)
	begin
		if @remoteserver = "%"
		begin
			/* 17680, "There are no remote servers defined." */
			exec sp_getmessage 17680, @msg out
			print @msg
			return (1)
		end

		/* 17681, "There are no remote logins for the remote server '%1!'." */
		exec sp_getmessage 17681, @msg out
		print @msg, @remoteserver
		return (1)
	end
end

/*
**  If no remotename given, get 'em all.
*/
if @remotename is null
begin
	select @remotename = "%"
end

else
begin
	if not exists (select *
			from master.dbo.sysremotelogins
			where isnull(remoteusername, "") like @remotename)
	begin
		if @remotename = "%"
		begin
			/* 17682, "There are no remotelogins defined." */
			exec sp_getmessage 17682, @msg out
			print @msg
			return (1)
		end

		/* 17683, "There are no remote logins for '%1!'." */
		exec sp_getmessage 17683, @msg out
		print @msg, @remotename
		return (1)
	end
end

/*
**  Check for empty results.
*/
if not exists (select *
		from master.dbo.sysremotelogins r, master.dbo.sysservers s
		where isnull(r.remoteusername, "") like @remotename
			and s.srvid = r.remoteserverid
				and s.srvname like @remoteserver)
begin
	if ((@remoteserver = '%') and (@remotename = '%'))
		/* 17684, "There are no remote logins." */
		exec sp_getmessage 17684, @msg out
	else 
		/* 17685, "There are no remote logins for '%1!' on remote server '%2!'." */
		exec sp_getmessage 17685, @msg out

	print @msg, @remotename, @remoteserver
	return (1)
end

/*
**  Select the information.
*/
declare @maplocal varchar(22)
declare @uselocal varchar(22)

/* 17686, "** mapped locally **" */
/* 17687, "** use local name **" */
exec sp_getmessage 17686, @maplocal out
exec sp_getmessage 17687, @uselocal out

select @sptlang = @@langid

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17070 and 17079
		and langid = @@langid)
	    select @sptlang = 0
end

select @len1 = max(datalength(s.srvname)),
       @len2 = max(datalength(isnull(r.remoteusername, @maplocal))),
       @len3 = max(datalength(isnull(suser_name(r.suid), @uselocal)))
	from master.dbo.sysservers s, master.dbo.sysremotelogins r
	where s.srvid = r.remoteserverid
		and s.srvname like @remoteserver
		and s.srvid > 0
		and isnull(r.remoteusername, "") like @remotename

if @sptlang = 0	/* us_english */
	if (@len1 > 22 or @len2 > 22 or @len3 > 22)
	    select server = s.srvname,
		remote_user_name = isnull(r.remoteusername, @maplocal),
		local_user_name = isnull(suser_name(r.suid), @uselocal),
		options = name
	    	    from master.dbo.sysservers s, master.dbo.sysremotelogins r,
			master.dbo.spt_values v
	            where s.srvid = r.remoteserverid
			and s.srvname like @remoteserver
			and s.srvid > 0
			and isnull(r.remoteusername, "") like @remotename
			and v.type = "F"
			and v.number = r.status
		    order by server, remote_user_name
	else
	    select server = convert(char(22), s.srvname),
		remote_user_name = 
		    convert(char(22), isnull(r.remoteusername, @maplocal)),
		local_user_name = 
		    convert(char(22), isnull(suser_name(r.suid), @uselocal)),
		options = name
	    	    from master.dbo.sysservers s, master.dbo.sysremotelogins r,
			master.dbo.spt_values v
	            where s.srvid = r.remoteserverid
			and s.srvname like @remoteserver
			and s.srvid > 0
			and isnull(r.remoteusername, "") like @remotename
			and v.type = "F"
			and v.number = r.status
		    order by server, remote_user_name
else /* non us_english */
	if (@len1 > 22 or @len2 > 22 or @len3 > 22)
	    select server = s.srvname,
		remote_user_name = isnull(r.remoteusername, @maplocal),
		local_user_name = isnull(suser_name(r.suid), @uselocal),
		options = m.description
		from master.dbo.sysservers s, master.dbo.sysremotelogins r,
			master.dbo.spt_values v, master.dbo.sysmessages m
		where s.srvid = r.remoteserverid
			and s.srvname like @remoteserver
			and s.srvid > 0
			and isnull(r.remoteusername, "") like @remotename
			and v.type = "F"
			and v.number = r.status
			and v.msgnum = m.error
			and m.langid = @sptlang
	    	order by server, remote_user_name
	else
	    select server = convert(char(22), s.srvname),
		remote_user_name = 
			convert(char(22), isnull(r.remoteusername, @maplocal)),
		local_user_name = 
			convert(char(22), isnull(suser_name(r.suid), @uselocal)),
		options = convert(char(16), m.description)
		from master.dbo.sysservers s, master.dbo.sysremotelogins r,
			master.dbo.spt_values v, master.dbo.sysmessages m
		where s.srvid = r.remoteserverid
			and s.srvname like @remoteserver
			and s.srvid > 0
			and isnull(r.remoteusername, "") like @remotename
			and v.type = "F"
			and v.number = r.status
			and v.msgnum = m.error
			and m.langid = @sptlang
	    	order by server, remote_user_name
return (0)
go
exec sp_procxmode 'sp_helpremotelogin', 'anymode'
go
grant execute on sp_helpremotelogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpsegment')
begin
	drop procedure sp_helpsegment
end
go
print "Installing sp_helpsegment"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */
/*
** Messages for "sp_helpsegment"        17nnn
**
** 17520, "There is no such segment as '%1!'."
*/
create procedure sp_helpsegment
@segname varchar(30) = NULL		/* segment name */
as

declare @segbit         int,    /* this is the bit version of the segment # */
	@segment        int,    /* the segment number of the segment */
	@factor         float,   /* conversion factor to convert to MB */
	@msg		varchar(100) /* message holder */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

/*
**  If no segment name given, get 'em all.
*/
if @segname is null
begin
	select *
		from syssegments order by segment
	return (0)
end

/*
**  Make sure the segment exists
*/
if not exists (select *
	from syssegments
		where name = @segname)
begin
	/* 17520, "There is no such segment as '%1!'." */
	exec sp_getmessage 17520, @msg out
	print @msg, @segname
	return (1)
end

/*
**  Show the syssegment entry, then the fragments and size it is on,
**  then any dependent objects in the database.
*/
select *
	from syssegments
		where name = @segname

/*
**  Set the bit position for the segment.
*/
select @segment = segment
	from syssegments
		where name = @segname

/*
**  Now set the segments on @devname sysusages.
*/
if (@segment < 31)
	select @segbit = power(2, @segment)
else
	/*
	**  Since this is segment 31, power(2, 31) will overflow
	**  since segmap is an int.  We'll grab the machine-dependent
	**  bit mask from spt_values to set the right bit.
	*/
	select @segbit = low
		from master.dbo.spt_values
			where type = "E"
				and number = 2

/*
** Get factor for conversion of pages to megabytes from spt_values
*/
select @factor = convert(float, low) / 1048576.0
        from master.dbo.spt_values
        where number = 1 and type = "E"

/*
** Select the sizes of the segments
*/
select device = d.name,
	size = convert(varchar(20), round((sum(u.size) * @factor), 0)) + "MB",
	free_pages = sum(curunreservedpgs(db_id(), u.lstart, u.unreservedpgs))
	from master.dbo.sysusages u, master.dbo.sysdevices d
                where u.segmap & @segbit = @segbit
                        and u.dbid = db_id()
                        and d.status & 2 = 2
                        and d.low <= u.vstart
                        and d.high >= u.vstart + (u.size - 1)
                group by d.name order by d.name

/*
** Select the dependant objects
*/
if exists (select *
		from sysindexes i, syssegments s
			where s.name = @segname
				and s.segment = i.segment)
begin
	select table_name = object_name(i.id), index_name = i.name, i.indid
		from sysindexes i, syssegments s
			where s.name = @segname
				and s.segment = i.segment
		order by table_name, indid
end

return (0)
go
exec sp_procxmode 'sp_helpsegment', 'anymode'
go
grant execute on sp_helpsegment to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpsort')
begin
	drop procedure sp_helpsort
end
go
print "Installing sp_helpsort"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */
/*
** Messages for "sp_helpsort"           17690
**
** 17690, "Character Set = "
** 17691, "Sort Order = "
** 17692, "Sort Order Description"
** 17693, "Characters, in Order"
** 17694, "Class 2 Character Set"
*/
create procedure sp_helpsort
AS
set nocount on

declare @sortid tinyint, @charid tinyint, @status tinyint
declare @csclass int
declare @image binary(1)
declare @count int, @end_flag int
    

declare @string varchar(66)
declare @msg varchar(100)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

create table #helpsort3 (string varchar(66))

/*
** Get the sortorder ID, character set ID, and status
*/
select @sortid = value from master..syscurconfigs where config = 123
select @charid = value from master..syscurconfigs where config = 131
select @image = convert(binary(1), definition)
    	from master.dbo.syscharsets where id = @sortid and csid = @charid

/*
** Get the name and description of the character set and sort order
*/


if (@sortid is NULL)
 BEGIN
    select @sortid = 0, @charid = 0, @status = 0, @csclass = 0
	/* 17690, "Character Set = " */
    exec sp_getmessage 17690, @msg out
    insert #helpsort3 values (@msg + " 0, ascii_8")
    insert #helpsort3 values ("    8-bit ASCII Character Set - System Default")
	/* 17691, "Sort Order = " */
    exec sp_getmessage 17691, @msg out
    insert #helpsort3 values (@msg + " 0, bin_ascii_8")
    insert #helpsort3 values ("    Binary Ordering - System Default")
 END
else
 BEGIN
    select @status = convert(tinyint, @image)

	/* 17690, "Character Set = " */
    exec sp_getmessage 17690, @msg out
    select @string = @msg + " " + convert(varchar(4), id) + ", " + name,
	   @csclass = type
	    from master.dbo.syscharsets 
	    where id = @charid

    insert into #helpsort3 values (@string)

    select @count = 1
    select @end_flag = 1

    while (@end_flag != 0)
    begin
	    select @string = substring(description, @count, 62)
		    from master.dbo.syscharsets 
		    where id = @charid
	    select @end_flag = isnull(ascii(@string), 0)

	    if (@end_flag != 0)
	    begin
		    select @string = "    " + @string
		    insert #helpsort3 values (@string)
	    end
	    select @count = @count + 62
    end

    /* Check if class 2 character set.  If so, tell 'em. */
    if (@csclass = 1002)
    begin
	/* 17694, "Class 2 Character Set" */
	exec sp_getmessage 17694, @msg out
    	insert #helpsort3 values ("    " + @msg)
    end

	/* 17691, "Sort Order = " */
    exec sp_getmessage 17691, @msg out
    select @string = @msg + " " + convert(varchar(4), id) + ", " + name
	    from master.dbo.syscharsets 
	    where id = @sortid and csid = @charid

    insert into #helpsort3 values (@string)

    select @count = 1
    select @end_flag = 1

    while (@end_flag != 0)
    begin
	    select @string = substring(description, @count, 62)
		    from master.dbo.syscharsets 
		    where id = @sortid and csid = @charid
	    select @end_flag = isnull(ascii(@string), 0)

	    if (@end_flag != 0)
	    begin
		    select @string = "    " + @string
		    insert #helpsort3 values (@string)
	    end

	    select @count = @count + 62
    end
END

/* 17692, "Sort Order Description" */
exec sp_getmessage 17692, @msg out
print @msg
select "" = string from #helpsort3

/*
** If we have a class 2 character set, then we are unable 
** to output the multi-byte characters in their proper
** sort sequence from here... we're done.
*/
if (@csclass = 1002)
begin
	return (0)
end

/*
** Build the sorted list of printable characters for this sort order.
** If it's not stored in spt_values yet, then put the results in there.
*/
if not exists
(select * from master.dbo.spt_values where type = 'Z' and low = @charid and high = @sortid)
BEGIN
    
    create table #helpsort1 (char_val char(1))



    if @charid = 0       /* ascii_8 has printable chars from 32-126 */
        begin
                select @count = 32
                while @count <= 126
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end

        end

    if @charid = 1      /* iso_1 has printable chars from 32-126 and 160-255 */
        begin
                select @count = 32
                while @count <= 126
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end

                select @count = 160
                while @count <= 255
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end
        end


    if @charid = 2      /* cp850 has printable chars from 32-255 */
        begin

                select @count = 32
                while @count <= 255
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end
        end

    if @charid = 3      /* cp437 has printable chars from 32-255 */
        begin
                select @count = 32
                while @count <= 255
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end
        end
    
    if @charid = 4      /* roman8 has printable chars from 32-126 and 161-254 */
        begin
                select @count = 32
                while @count <= 126
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end

                select @count = 161
                while @count <= 254
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end
        end
    
    if @charid = 5      /* mac has printable chars from 32-126 and 128-216 */
        begin
                select @count = 32
                while @count <= 126
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end

                select @count = 128
                while @count <= 216
                begin
                        insert #helpsort1 (char_val)
                                values (char(@count))
                        select @count = @count + 1
                end
        end
    
     if @charid > 5     /* User Character Set Not recognised by sp_helpsort */
        begin

                select "Unknown Character Set : " + name 
			from master.dbo.syscharsets
                                where id = @sortid and type = 2001
                return (0)
    
        end

    
    select (char_val) into #helpsort2
    	from #helpsort1
        order by char_val
    
    declare @char char(1)
    declare @char_str varchar(20)
    declare @incr int
    declare @seq_num int
    declare @rel char(1)
    declare @old_char char(1)
    
    select @char = char(0), @seq_num = 0, @count = 0, @incr = 8, @end_flag = 1
    select @rel = " ", @old_char = NULL
    
    set rowcount 1
   
    while @end_flag != 0
    begin
    
        select @char_str = ""
    
	/* If PST_NOTUNIQ is set, then possibly caseless */
	if (@status & 8 = 8)
            while (@count < @incr  and  @end_flag != 0)
            begin
                select @char = char_val
    	            from #helpsort2
                    where char_val >= @char
                select @end_flag = @@rowcount

		if (@end_flag != 0)
		begin
		    if (@char = @old_char)
			select @rel = "="
		    else
			select @rel = " "

		    select @old_char = @char
		    select @char_str = @char_str + @rel + @char
                    delete from #helpsort2 where ascii(@char) = ascii(char_val)
    
		    select @count = @count + 1
		end
            end
	else
            while (@count < @incr  and  @end_flag != 0)
            begin
                select @char = char_val
    	            from #helpsort2
                    where char_val > @char
                select @end_flag = @@rowcount

		if (@end_flag != 0)
		begin
		    select @char_str = @char_str + @rel + @char
                    delete from #helpsort2 where ascii(@char) = ascii(char_val)

		    select @count = @count + 1
		end
            end

        select @incr = @incr + 8, @seq_num = @seq_num + 1
        insert master.dbo.spt_values (name, number, type, low, high) 
		values (@char_str, @seq_num, 'Z', @charid, @sortid)
    end
    
    set rowcount 0
    
END

/*
** Display the sorted list of characters.
*/
select @count = 1
select @end_flag = 1
select @incr = 5

truncate table #helpsort3

while @end_flag != 0
BEGIN
	select @string = ""

	while @count < @incr
	begin
		select @string = @string + substring(name, 2, 19) 
			from master.dbo.spt_values
			where type = 'Z' and number = @count and low = @charid
				and high = @sortid
		select @end_flag = @@rowcount
		select @count = @count + 1
	end

	select @incr = @incr + 4

	insert into #helpsort3 values (@string)
END

/* 17693, "Characters, in Order" */
exec sp_getmessage 17693, @msg out
print @msg
select "" = string from #helpsort3

set nocount off

return(0)
go
exec sp_procxmode 'sp_helpsort', 'anymode'
go
grant execute on sp_helpsort to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpserver')
begin
	drop procedure sp_helpserver
end
go
print "Installing sp_helpserver"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/fixindex */
/*
** Messages for "sp_helpserver"
**
** 17270, "There is not a server named '%1!'."
** 17680, "There are no remote servers defined."
*/
create procedure sp_helpserver
@server varchar(30) = NULL		/* server name */
as

declare	@msg	varchar(100)
declare @len1 int, @len2 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

/*
**  If no server name given, get 'em all.
*/
if @server is null
begin
	select @server = "%"
end

/*
**  Does the server exist?
*/
if not exists (select *
		from master.dbo.sysservers 
			where srvname like @server
				or srvnetname like @server)
begin
	if @server = "%"
		/* 17680, "There are no remote servers defined." */
		exec sp_getmessage 17680, @msg out
	else 
		/* 17270, "There is not a server named '%1!'." */
		exec sp_getmessage 17270, @msg out
	print @msg, @server
	return (1)
end
	
/*
**  Display server information.
**  First put it into a temp table so we can examine the status 
**  bits and turn them into english.
*/
create table #spt_server
(
	name	varchar(30),
	network	varchar(30),
	status	varchar(255),
	id	smallint
)

/*
**  Initialize #spt_server from sysservers.
*/
insert into #spt_server
        select s.srvname, s.srvnetname, "",
                id = s.srvid
	from master.dbo.sysservers s
		where (s.srvname like @server
			or s.srvnetname like @server)


/* 
**  Now for each nonlocal server in #spt_server, build the server
**  status description.  Logic patterned after helpdb.
*/

declare @cursrvid smallint	/* the current server we're working on. */
declare @srvdesc varchar(255)	/* the server description string. */
declare @bitdesc varchar(30)    /* the bit description for the server */

/*
**  Set @cursrvid to the first server id.
*/
select @cursrvid = min(id)
	from #spt_server
	where id != 0

/*
**  Parse the status.
*/
while @cursrvid is not NULL
begin
	/*
	**  Initialize @srvdesc.
	*/
	select @srvdesc = ""

	/* 
	**  Check timeout bit.  Note special kludgy handling
	**  due to previous definition of timeout and no timeout
	**  in spt_values.
	*/
	select @bitdesc = null
	select @bitdesc = v.name
		from master.dbo.spt_values v
			where v.type = "A"
				and v.number = 0

	if exists (select * 
		from master.dbo.spt_values v, master.dbo.sysservers s
			where s.srvid = @cursrvid
				and s.srvstatus & v.number = 1)
	begin
		select @srvdesc = "no " + @bitdesc
	end
	else
	begin
		select @srvdesc = @bitdesc
	end

	/* 
	**  Check network password encryption status.
	*/
	select @bitdesc = null
	select @bitdesc = v.name
		from master.dbo.spt_values v
			where v.type = "A"
				and v.number = 2

	if exists (select * 
		from master.dbo.spt_values v, master.dbo.sysservers s
			where s.srvid = @cursrvid
				and s.srvstatus & v.number = 2)
	begin
		if @srvdesc != ""
			select @srvdesc = @srvdesc + ", " + @bitdesc
		else
			select @srvdesc = @bitdesc
	end
	else
	begin
		if @srvdesc != ""
			select @srvdesc = @srvdesc + ", no " + @bitdesc
		else
			select @srvdesc = "no " + @bitdesc
	end

	/*
	**  Save the description.
	*/
	update #spt_server
		set status = @srvdesc
			from #spt_server
				where id = @cursrvid

	/*
	**  Now get the next, if any, server id.
	*/
	select @cursrvid = min(id)
		from #spt_server
			where id > @cursrvid
end

/*
**  Display the information we got.
*/
select @len1 = max(datalength(network)),
       @len2 = max(datalength(status))
	from #spt_server

if (@len1 > 28 or @len2 > 11)
    select name, network_name = network, status, id = convert(char(5), id)
		from #spt_server
	order by name
else
    select name, network_name = convert(char(28), network), 
	status = convert(char(11), status), id = convert(char(5), id)
		from #spt_server
	order by name

return (0)
go
exec sp_procxmode 'sp_helpserver', 'anymode'
go
grant execute on sp_helpserver to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_markreport')
begin
	drop procedure sp_markreport
end
go
print "Installing sp_markreport"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/lock */

/*
** Messages for "sp_markreport"         17712
**
** 17712, "Report must be in your current database."
** 17713, "No such report exists."
*/

create procedure sp_markreport
@reportname varchar(92)		/* proc name we want to mark as report */
as

declare @msg  varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Make sure the @reportname is local to the current database.
*/
if @reportname like "%.%.%" and
	substring(@reportname, 1, charindex(".", @reportname) - 1) != db_name()
begin
	/*
	** 17712, "Report must be in your current database."
	*/
	exec sp_getmessage 17712, @msg output
	print @msg
	return (1)
end

/*
**  Make sure that it actually exists as a sproc.
*/
if not exists (select *
		from sysobjects
			where id = object_id(@reportname)
			and sysstat & 7 = 4	/* stored procedure */
			and uid = user_id())
begin
	/*
	** 17713, "No such report exists."
	*/
	exec sp_getmessage 17713, @msg output
	print @msg
	return (1)
end

update sysobjects
	set userstat = userstat | -32768	/* high bit means report */
		from sysobjects
			where id = object_id(@reportname)
			and sysstat & 7 = 4		/* stored procedure */
			and uid = user_id()

return (0)
go
exec sp_procxmode 'sp_markreport', 'anymode'
go
grant execute on sp_markreport to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_monitor')
begin
	drop procedure sp_monitor
end
go
print "Installing sp_monitor"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/lock */

/*
** Messages for "sp_monitor"            17nnn
**
** 17260, "Can't run %1! from within a transaction."
*/

create procedure sp_monitor
as

/*
**  Declare variables to be used to hold current monitor values.
*/
declare @now 		datetime
declare @cpu_busy 	int
declare @io_busy	int
declare @idle		int
declare @pack_received	int
declare @pack_sent	int
declare @pack_errors	int
declare @connections	int
declare @total_read	int
declare @total_write	int
declare @total_errors	int
declare @engonline	int
declare @oldcpu_busy 	int	/* used to see if DataServer has been rebooted */
declare @interval	int
declare @mspertick	float	/* milliseconds per tick */
declare @msg	varchar(250)	/* Message text */

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/* 17260, "Can't run %1! from within a transaction." */
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_monitor"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
** check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  Set @mspertick.  This is just used to make the numbers easier to handle
**  and avoid overflow.
*/

select @mspertick = (@@timeticks / 1000.0)
/*
**  Set engonline to number of engines currently on line (so busy/idle
**  figures are correct). If this changes under us, the figures will not
**  necessarily be accurate for the next sp_monitor call; this should not
**  be a tremendous problem.
*/
 
select @engonline = count(*) from master.dbo.sysengines

/*
**  Get current monitor values.
*/
select
	@now = getdate(),
	@cpu_busy = @@cpu_busy,
	@io_busy = @@io_busy,
	@idle = @@idle,
	@pack_received = @@pack_received,
	@pack_sent = @@pack_sent,
	@connections = @@connections,
	@pack_errors = @@packet_errors,
	@total_read = @@total_read,
	@total_write = @@total_write,
	@total_errors = @@total_errors

/*
**  Check to see if DataServer has been rebooted.  If it has then the
**  value of @@cpu_busy will be less than the value of spt_monitor.cpu_busy.
**  If it has update spt_monitor.
*/
select @oldcpu_busy = cpu_busy
	from master.dbo.spt_monitor
if @oldcpu_busy > @cpu_busy
begin
	update master.dbo.spt_monitor
		set
			lastrun = @now,
			cpu_busy = @cpu_busy,
			io_busy = @io_busy,
			idle = @idle,
			pack_received = @pack_received,
			pack_sent = @pack_sent,
			connections = @connections,
			pack_errors = @pack_errors,
			total_read = @total_read,
			total_write = @total_write,
			total_errors = @total_errors
end

/*
**  Now print out old and new monitor values.
*/
set nocount on
select @interval = datediff(ss, lastrun, @now)
	from master.dbo.spt_monitor
/* To prevent a divide by zero error when run for the first
** time after boot up
*/
if @interval = 0
        select @interval = 1
select last_run = lastrun, current_run = @now, seconds = @interval
	from master.dbo.spt_monitor
select
cpu_busy = convert(char(25),
	   	   convert(varchar(11),
			   convert(int,
				   (@cpu_busy * (@mspertick / 1000))))
		+ "("
		+  convert(varchar(11),
			   convert(int,
				   ((@cpu_busy - cpu_busy) * (@mspertick / 1000))
				  / @engonline))
		+ ")"
		+ "-"
		+  convert(varchar(11),
			   convert(int,
				   ((((@cpu_busy - cpu_busy)
				     * (@mspertick / 1000))
				    / @engonline) * 100)
				   / @interval))
		+ "%"),

io_busy = convert(char(25),
		  convert(varchar(11),
			  convert(int,
				  (@io_busy * (@mspertick / 1000))
				  / @engonline))
		+ "("
		+ convert(varchar(11),
			  convert(int,
				  ((@io_busy - io_busy) * (@mspertick / 1000))
				  / @engonline))
		+ ")"
		+ "-"
		+ convert(varchar(11),
			  convert(int,
				  ((((@io_busy - io_busy) * (@mspertick / 1000))
				    / @engonline)
				   * 100)
				  / @interval))
		+ "%"),
idle =    convert(char(25),
	          convert(varchar(11),
		          convert(int,
			          (@idle * (@mspertick / 1000))
			          / @engonline))
		+ "("
		+ convert(varchar(11),
			  convert(int,
				  ((@idle - idle) * (@mspertick / 1000))
				  / @engonline))
		+ ")"
		+ "-"
		+ convert(varchar(11),
			  convert(int,
				  ((((@idle - idle) * (@mspertick / 1000))
				    / @engonline)
				   * 100)
				  / @interval))
		+ "%")

from master.dbo.spt_monitor

select
	packets_received = convert(char(25), convert(varchar(11), @pack_received) + "(" +
		convert(varchar(11), @pack_received - pack_received) + ")"),
	packets_sent = convert(char(25), convert(varchar(11), @pack_sent) + "(" +
		convert(varchar(11), @pack_sent - pack_sent) + ")"),
	packet_errors = convert(char(25), convert(varchar(11), @pack_errors) + "(" +
		convert(varchar(11), @pack_errors - pack_errors) + ")")
from master.dbo.spt_monitor

select
	total_read = convert(char(19), convert(varchar(11), @total_read) + "(" +
		convert(varchar(11), @total_read - total_read) + ")"),
	total_write = convert(char(19), convert(varchar(11), @total_write) + "(" +
		convert(varchar(11), @total_write - total_write) + ")"),
	total_errors = convert(char(19), convert(varchar(11), @total_errors) + "(" +
		convert(varchar(11), @total_errors - total_errors) + ")"),
	connections = convert(char(18), convert(varchar(11), @connections) + "(" +
		convert(varchar(11), @connections - connections) + ")")
from master.dbo.spt_monitor

/*
**  Now update spt_monitor
*/
update master.dbo.spt_monitor
	set
		lastrun = @now,
		cpu_busy = @cpu_busy,
		io_busy = @io_busy,
		idle = @idle,
		pack_received = @pack_received,
		pack_sent = @pack_sent,
		connections = @connections,
		pack_errors = @pack_errors,
		total_read = @total_read,
		total_write = @total_write,
		total_errors = @total_errors

return (0)
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_pkeys')
begin
	drop procedure sp_pkeys
end
go
print "Installing sp_pkeys"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*
** note: there is one raiserror message: 18040
**
** messages for "sp_pkeys"               18039, 18040
**
** 17461, "Object does not exist in this database."
** 18039, "table qualifier must be name of current database."
** 18040, "catalog procedure %1! can not be run in a transaction.", sp_pkeys
**
*/

create procedure sp_pkeys
			   @table_name		varchar(32),
			   @table_owner 	varchar(32) = null,
			   @table_qualifier varchar(32) = null 
as
declare @msg varchar(255)
declare @keycnt smallint
declare @indexid smallint
declare @i int
declare @id int
declare @uid smallint
select @id = NULL


	set nocount on

	if (@@trancount = 0)
	begin
		set chained off
	end
	else
	begin	
		/* if inside a transaction */
		/* catalog procedure sp_pkeys can not be run in a transaction.*/
		exec sp_getmessage 18040, @msg output
		raiserror 18040 @msg, "sp_pkeys"
		return (1)
	end

	set transaction isolation level 1

	if @table_qualifier is not null
	begin
		if db_name() != @table_qualifier
		begin	
			/* if qualifier doesn't match current database */
			/* "table qualifier must be name of current database"*/
			exec sp_getmessage 18039, @msg output
			print @msg 
			return (1)
		end
	end

	if @table_owner is null
	begin
		select @id = id , @uid = uid
		from sysobjects 
		where name = @table_name
			and uid = user_id()
		if (@id is null)
		begin
			select @id = id ,@uid = uid
			from sysobjects 
			where name = @table_name
			and uid = 1
		end
	end
	else
	begin
		select @id = id , @uid = uid
		from sysobjects 
		where name = @table_name and uid = user_id(@table_owner)
	end
	
	if (@id is null)
	begin	
		/* 17461, "Object does not exist in this database." */
		exec sp_getmessage 17461, @msg output
		print @msg 
		return (1)
	end

	create table #pkeys(
			 table_qualifier varchar(32),
			 table_owner     varchar(32),
			 table_name      varchar(32),
			 column_name     varchar(32),
			 key_seq	 smallint)


/*
**  now we search for primary key (only declarative) constraints
**  There is only one primary key per table.
*/

	select @keycnt = keycnt, @indexid = indid
	from   sysindexes
	where  id = @id
	and indid > 0 /* make sure it is an index */
	and status2 & 2 = 2 /* make sure it is a declarative constr */
	and status & 2048 = 2048 /* make sure it is a primary key */

/*
**  For non-clustered indexes, keycnt as returned from sysindexes is one
**  greater than the actual key count. So we need to reduce it by one to
**  get the actual number of keys.
*/

	if (@indexid >= 2)
	begin
		select @keycnt = @keycnt - 1
	end

	select @i = 1

	while @i <= @keycnt
	begin
		insert into #pkeys values
		(db_name(), user_name(@uid), @table_name,
			index_col(@table_name, @indexid, @i, @uid), @i)
		select @i = @i + 1
	end

	select table_qualifier, table_owner, table_name, column_name, key_seq
	from #pkeys
	order by table_qualifier, table_owner, table_name, key_seq
	
	return (0)
go
exec sp_procxmode 'sp_pkeys', 'anymode'
go
grant execute on sp_pkeys to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_placeobject')
begin
	drop procedure sp_placeobject
end
go
print "Installing sp_placeobject"
go

/* Sccsid = "@(#) generic/sproc/src/%M% %I% %G%" */
/*	5.0	14.2	11/12/91	sproc/src/placeobject */

/*
** Messages for "sp_placeobject"        17730
**
** 17460, "Object must be in the current database."
** 17520, "There is no such segment as '%1!'."
** 17730, "Use sp_logdevice to move syslogs table."
** 17731, "You can't move system tables."
** 17732, "You do not own table '%1!'."
** 17733, "There is no table named '%1!'."
** 17734, "There is no index named '%1!' for table '%2!'."
** 17735, "'%1!' is now on segment '%2!'."
** 17736, "You can't place a user table/index to logsegment."
** 17737, "Partitioned objects cannot be moved."
*/

create procedure sp_placeobject
@segname	varchar(30),	/* segment name */
@objname	varchar(123)	/* object name */
as

declare	@msg		varchar(250)	/* message text */
declare @tabname	varchar(92)	/* table name, may be qualified */
declare @indexname	varchar(30)	/* index name, unqualified */
declare	@indexid	smallint	/* index ID */
declare	@segment	smallint	/* segment number */
declare @procval 	int		/* 1 if user has sa_role, 0 otherwise */
declare	@revobjname	varchar(123)	/* reverse of @objname */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see if the segment exists.
*/
select @segment = segment
	from syssegments
	where name = @segname
if @segment is null
begin
	/*
	** 17520, "There is no such segment as '%1!'."
	*/
	exec sp_getmessage 17520, @msg output
	print @msg, @segname
	return (1)
end

/*
**  Are we dealing with a table or its index?
*/
if (@objname like "%.%") and (object_id(@objname) is null)
begin
	/* @objname is in the form [database.][owner.]table.index */
	select @revobjname = reverse(@objname)
	select
		@tabname = reverse(substring(@revobjname,
			charindex(".", @revobjname) + 1, 92)),
		@indexname = reverse(substring(@revobjname, 1,
			charindex(".", @revobjname) - 1))
end
else
begin
	/* @objname is in the form [database.][owner.]table */
	select @tabname = @objname, @indexname = null
end

/*
**  Make sure the table is local to the current database.
*/
if @tabname like "%.%.%" and
	substring(@tabname, 1, charindex(".", @tabname) - 1) != db_name()
begin
	/* 17460, "Object must be in the current database." */
	exec sp_getmessage 17460, @msg out
	print @msg
	return  (1)
end

/*
**  make sure the table exists.
*/
if (object_id(@tabname) is null)
begin
	/*
	** 17733, "There is no table named '%1!'."
	*/
	exec sp_getmessage 17733, @msg output
	print @msg, @tabname
	return (1)
end

/*
**  Can't use placeobject to move syslogs.
*/
if (object_id(@tabname) = 8)
begin
	/*
	** 17730, "Use sp_logdevice to move syslogs table."
	*/
	exec sp_getmessage 17730, @msg output
	print @msg
	return (1)
end

/*
**  Can't move system tables.
*/
if (object_id(@tabname) < 100)
begin
	/*
	** 17731, "You can't move system tables."
	*/
	exec sp_getmessage 17731, @msg output
	print @msg
	return (1)
end

/*
**  Can't move partitioned tables. Indexes on partitioned tables
**  can be moved because indexes are not partitioned.
*/
if @indexname is null and
	exists (select *
                   from syspartitions
                   where id = object_id(@tabname))
begin
	/*
	** 17737, "Partitioned objects cannot be moved."
	*/
	exec sp_getmessage 17737, @msg output
	print @msg
	return (1)
end


/*
**  Only the Database Owner (DBO) or Table Owner (TBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/
if user_id() != 1
begin
	if not exists (select * from sysobjects
		where id = object_id(@tabname) and uid = user_id())
	begin
		if (proc_role("sa_role") != 1)
		begin
			/*
			** 17732, "You do not own table '%1!'."
			*/
			exec sp_getmessage 17732, @msg output
			print @msg, @tabname
			return (1)
		end
	end
end

/* If user has sa role audit this as a successful sa 
** command execution.
*/ 
if charindex("sa_role",show_role()) > 0
	select @procval = proc_role("sa_role") 

/*
**  If we are dealing with an index, make sure it exists.
*/
if @indexname is not  null and
	not exists (select * from sysindexes
	where id = object_id(@tabname) and name = @indexname)
begin
	/*
	** 17734, "There is no index named '%1!' for table '%2!'."
	*/
	exec sp_getmessage 17734, @msg output
	print @msg, @indexname, @tabname
	return (1)
end


if (@segname = "logsegment")
begin
  	exec sp_getmessage 17736, @msg output
	print @msg
	return (1)
end

  
/*
**  Everything's ok so change the segment for the object.
*/
if @indexname is null
begin
	select @indexid = indid
		from sysindexes
		where id = object_id(@tabname) and indid < 2
end
else
begin
	select @indexid = indid
		from sysindexes
		where id = object_id(@tabname) and name = @indexname
end

update sysindexes
	set segment = @segment
	from sysindexes
	where id = object_id(@tabname) and indid = @indexid

declare @dbname	varchar(30)
select @dbname = db_name()
dbcc dbrepair (@dbname, remap)
/*
** 17735, "'%1!' is now on segment '%2!'."
*/
exec sp_getmessage 17735, @msg output
print @msg, @objname, @segname

return (0)
go
exec sp_procxmode 'sp_placeobject', 'anymode'
go
grant execute on sp_placeobject to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_primarykey')
begin
	drop procedure sp_primarykey
end
go
print "Installing sp_primarykey"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/password */

/*
** Messages for "sp_primarykey"         17740
**
** 17390, "Table or view name must be in 'current' database." 
** 17492, "The table or view named doesn't exist in the current database." 
** 17740, "Only the owner of the table may define a primary key."
** 17741, "Primary key already exists on table -- drop key first."
** 17742, "The table has no such first column."
** 17743, "The table has no such second column."
** 17744, "The table has no such third column."
** 17745, "The table has no such fourth column."
** 17746, "The table has no such fifth column."
** 17747, "The table has no such sixth column."
** 17748, "The table has no such seventh column."
** 17749, "The table has no such eighth column."
** 17750, "New primary key added."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_primarykey
@tabname  varchar(92),			/* table name that has the key */
@col1     varchar(30), 			/* columns that make up the key */
@col2     varchar(30) = NULL,
@col3     varchar(30) = NULL,
@col4     varchar(30) = NULL,
@col5     varchar(30) = NULL,
@col6     varchar(30) = NULL,
@col7     varchar(30) = NULL,
@col8     varchar(30) = NULL
as

declare @uid smallint			/* owner id of the object */
declare @cnt smallint			/* howmany columns in key */
declare @key1 tinyint			/* colids of the columns in the key */
declare @key2 tinyint
declare @key3 tinyint
declare @key4 tinyint
declare @key5 tinyint
declare @key6 tinyint
declare @key7 tinyint
declare @key8 tinyint
declare @msg  varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see that the tabname is local.
*/
if @tabname like "%.%.%" and
	substring(@tabname, 1, charindex(".", @tabname) - 1) != db_name()
begin
	/*
	** 17390, "Table or view name must be in 'current' database." 
	*/
	exec sp_getmessage 17390, @msg output
	print @msg
	return (1)
end

/*
**  See if we can find the object.  It must be a system table, user table,
**  or view.  The low 3 bits of sysobjects.sysstat indicate what the 
**  object type is -- it's more reliable than using sysobjects.type which
**  could change.
*/
if not exists (select *
	from sysobjects
		where id = object_id(@tabname)
			and (sysstat & 7 = 1		/* system table */
				or sysstat & 7 = 2	/* view */
				or sysstat & 7 = 3))	/* user table */
begin
	/*
	** 17492, "The table or view named doesn't exist in the current database." 
	*/
	exec sp_getmessage 17492, @msg output
	print @msg
	return (1)
end 

/*
**  Check to see that object owner is adding the key.
*/
select @uid = uid
	from sysobjects
		where id = object_id(@tabname)
			and (sysstat & 7 = 1            /* system table */
				 or sysstat & 7 = 2      /* view */
				  or sysstat & 7 = 3)     /* user table */
if @uid != user_id()
begin
	/*
	** 17740, "Only the owner of the table may define a primary key."
	*/
	exec sp_getmessage 17740, @msg output
	print @msg
	return (1)
end

/*
**  See if the primary key exists already.  Syskeys.type = 1 indicates
**  a primary key.
*/
if exists (select *
		from syskeys
			where id = object_id(@tabname)
				and type = 1)
begin
	/*
	** 17741, "Primary key already exists on table -- drop key first."
	*/
	exec sp_getmessage 17741, @msg output
	print @msg
	return (1)
end

/*
**  Now check out each column argument to verify it's existence.
*/
select @cnt = 1, @key1 = colid
	from syscolumns
		where name = @col1 
			and id = object_id(@tabname)
if @key1 is NULL
begin
	/*
	** 17742, "The table has no such first column."
	*/
	exec sp_getmessage 17742, @msg output
	print @msg
	return (1)
end

if @col2 is not NULL
begin
	select @cnt = @cnt + 1, @key2 = colid
		from syscolumns
			where name = @col2 
				and id = object_id(@tabname)
	if @key2 is NULL
	begin
		/*
		** 17743, "The table has no such second column."
		*/
		exec sp_getmessage 17743, @msg output
		print @msg
		return (1)
	end
end
else goto doinsert

if @col3 is not NULL
begin
	select @cnt = @cnt + 1, @key3 = colid
		from syscolumns
			where name = @col3 
				and id = object_id(@tabname)
	if @key3 is NULL
	begin
		/*
		** 17744, "The table has no such third column."
		*/
		exec sp_getmessage 17744, @msg output
		print @msg
		return (1)
	end
end
else goto doinsert

if @col4 is not NULL
begin
	select @cnt = @cnt + 1, @key4 = colid
		from syscolumns
			where name = @col4 
				and id = object_id(@tabname)
	if @key4 is NULL
	begin
		/*
		** 17745, "The table has no such fourth column."
		*/
		exec sp_getmessage 17745, @msg output
		print @msg
		return (1)
	end
end
else goto doinsert

if @col5 is not NULL
begin
	select @cnt = @cnt + 1, @key5 = colid
		from syscolumns
			where name = @col5 
				and id = object_id(@tabname)
	if @key5 is NULL
	begin
		/*
		** 17746, "The table has no such fifth column."
		*/
		exec sp_getmessage 17746, @msg output
		print @msg
		return (1)
	end
end
else goto doinsert

if @col6 is not NULL
begin
	select @cnt = @cnt + 1, @key6 = colid
		from syscolumns
			where name = @col6 
				and id = object_id(@tabname)
	if @key6 is NULL
	begin
		/*
		** 17747, "The table has no such sixth column."
		*/
		exec sp_getmessage 17747, @msg output
		print @msg
		return (1)
	end
end
else goto doinsert

if @col7 is not NULL
begin
	select @cnt = @cnt + 1, @key7 = colid
		from syscolumns
			where name = @col7 
				and id = object_id(@tabname)
	if @key7 is NULL
	begin
		/*
		** 17748, "The table has no such seventh column."
		*/
		exec sp_getmessage 17748, @msg output
		print @msg
		return (1)
	end
end
else goto doinsert

if @col8 is not NULL
begin
	select @cnt = @cnt + 1, @key8 = colid
		from syscolumns
			where name = @col8 
				and id = object_id(@tabname)
	if @key8 is NULL
	begin
		/*
		** 17749, "The table has no such eighth column."
		*/
		exec sp_getmessage 17749, @msg output
		print @msg
		return (1)
	end
end

/*
**  Type 1 is a primary key, 2 is a foreignkey, and 3 is a commonjoin.
*/
doinsert:

insert into syskeys
	(id, type, depid, keycnt, size, key1, key2, key3, key4, key5,
		key6, key7, key8)
values (object_id(@tabname), 1, NULL, @cnt, 0, @key1, @key2, @key3, @key4, 
		@key5, @key6, @key7, @key8)   

/*
** 17750, "New primary key added."
*/
exec sp_getmessage 17750, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_primarykey', 'anymode'
go
grant execute on sp_primarykey to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_recompile')
begin
	drop procedure sp_recompile
end
go
print "Installing sp_recompile"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/password */

/*
** Messages for "sp_recompile"          17760
**
** 17732, "You do not own table '%1!'." 
** 17390, "Table or view name must be in 'current' database."
** 17460, "Object must be in the current database."
** 17760, "'%1!' is a system table.  Sp_recompile cannot be used on system tables."
** 17761, "Object '%1!' is not a table."
** 17762, "Each stored procedure and trigger that uses table '%1!' will be recompiled the next time it is executed."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_recompile
@objname	varchar(92)
as

declare @type	smallint
declare @uid		smallint
declare @msg    varchar(250)
declare @tmp	int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

if @objname like '%%.%%.%%'
begin
	/*
	** 17390, "Table or view name must be in 'current' database."
	*/
	exec sp_getmessage 17390, @msg output
	print @msg
	return
end

if not exists (select *
			from sysobjects
				where id = object_id(@objname))
begin
	/*
	** 17460, "Object must be in the current database."
	*/
	exec sp_getmessage 17460, @msg output
	print @msg
	return
end

select @type = sysstat & 7, @uid = uid
	from sysobjects
		where id = object_id(@objname)
if @type = 1
begin
	/*
	** 17760, "'%1!' is a system table.  Sp_recompile cannot be used on system tables."
	*/
	exec sp_getmessage 17760, @msg output
	print @msg, @objname
	return
end
if @type != 3
begin
	/*
	** 17761, "Object '%1!' is not a table."
	*/
	exec sp_getmessage 17761, @msg output
	print @msg, @objname
	return
end

if user_id() != 1 and @uid != user_id()
begin
	/*
	** 17732, "You do not own table '%1!'." 
	*/
	exec sp_getmessage 17732, @msg output
	print @msg, @objname
	return
end

set nocount on

update sysobjects
set schemacnt = schemacnt + 1
where id = object_id(@objname)

/*
** Increment the schemacnt associated with cached des.
*/
select @tmp = schema_inc(object_id(@objname)) 

/*
** 17762, "Each stored procedure and trigger that uses table '%1!' will be recompiled the next time it is executed."
*/
exec sp_getmessage 17762, @msg output
print @msg, @objname
go
exec sp_procxmode 'sp_recompile', 'anymode'
go
grant execute on sp_recompile to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_remoteoption')
begin
	drop procedure sp_remoteoption
end
go
print "Installing sp_remoteoption"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/remoteoption */

/*
** Messages for "sp_remoteoption"       17770
**
** 17513, "There is no remote user '%1!' mapped to local user '%2!' from
**	the remote server '%3!'."
** 17260, "Can't run %1! from within a transaction."
** 17770, "Settable remote login options."
** 17771, "There is no remote user '%1!' mapped to local user '%2!' on
**	remote server '%3!'."
** 17772, "Usage: sp_remoteoption [remoteserver, loginame, remotename,
**	optname, {true | false}]"
** 17773, "Remote login option doesn't exist or can't be set by user."
** 17774, "Run sp_remoteoption with no parameters to see options."
** 17775, "Remote login option is not unique."
** 17777, "Option '%1!' turned on."
** 17778, "Option '%1!' turned off."
** 17431, "true"
** 17432, "false"
*/

create procedure sp_remoteoption
@remoteserver varchar(30) = NULL,	/* server name to change */
@loginame varchar(30) = NULL,		/* user's remote name */
@remotename varchar(30) = NULL,		/* user's local user name */
@optname varchar(20) = NULL,		/* option name to turn on/off */
@optvalue varchar(10) = NULL		/* true or false */
as

declare @statvalue 	smallint	/* number of option */
declare @optcount 	int		/* number of options like @optname */
declare	@msg		varchar(100)
declare @suid		smallint
declare @rname  	varchar(30)
declare @lname  	varchar(30)
declare @true		varchar(10)
declare @false  	varchar(10)
declare @sptlang	int
declare @whichone	int		/* Which language */

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sso role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sso_role") = 0)
	return (1)

select @sptlang = 0, @whichone = 0

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17070 and 17079
		and langid = @@langid)
	    select @sptlang = 0
end

/*
**  If no @server given, just list the possible remote login options.
**  Only certain status bits may be set or cleared.  
**	   settable                	    not settable
**      ------------------------------  --------------------------
**	trusted (1)
*/
if @remoteserver is null
begin
	/*
	** 17770, "Settable remote login options."
	*/
	exec sp_getmessage 17770, @msg output
	print @msg
	if @sptlang = 0
	    select remotelogin_option = name
		from master.dbo.spt_values
			where type = "F"
				and number in (1, 1)
				and number > 0
		order by name
	else
	    select remotelogin_option = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
			where type = "F"
				and number in (1, 1)
				and number > 0
				and msgnum = error
				and error between 17070 and 17079
				and langid = @sptlang
		order by name
	return (0)
end

/*
**  If @loginame is NULL then we want to set @suid = -1. Otherwise get
**  it real value.
*/
if @loginame is null
	select @suid = -1
else select @suid = suser_id(@loginame)

/*
**  Verify the server name, local, and remote names. 
*/
if not exists (select *
		from master.dbo.sysremotelogins r, master.dbo.sysservers s
			where r.remoteserverid = s.srvid
				and s.srvname = @remoteserver
				and r.remoteusername = @remotename
				and r.suid = @suid)
begin
	/*
	** 17771, "There is no remote user '%1!' mapped to local user '%2!' on
	**	remote server '%3!'."
	*/
	select @rname = isnull(@remotename, "NULL")
	select @lname = isnull(@loginame, "NULL")
	exec sp_getmessage 17771, @msg output
	print @msg, @rname, @lname, @remoteserver
	return (1)
end

/*
**  Check remaining parameters.
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
/* 17432, "false" */
exec sp_getmessage 17432, @false out
if @optname is NULL or lower(@optvalue) not in 
	("true", "false", @true, @false) or @optvalue is null
begin
	/*
	** 17772, "Usage: sp_remoteoption [remoteserver, loginame, remotename,
	**	optname, {true | false}]"
	*/
	exec sp_getmessage 17772, @msg output
	print @msg
	return (1)
end

/*
**  Use @optname and try to find the right option.
**  If there isn't just one, print appropriate diagnostics and return.
*/
select @optcount = count(*)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%" and type = "F"
			and number in (1, 1)
			and number > 0

/*
** If option not found, and language not english, then check some more
*/
if @optcount = 0 and @sptlang != 0
begin
    select @optcount = count(*)
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%" and type = "F"
			and number in (1, 1)
			and number > 0
			and error between 17070 and 17079
			and msgnum = error
			and langid = @sptlang
    select @whichone = 1
end

/*
**  If no option, show the user what the options are.
*/
if @optcount = 0
begin
	/*
	** 17773, "Remote login option doesn't exist or can't be set by user."
	*/
	exec sp_getmessage 17773, @msg output
	print @msg
	/*
	** 17774, "Run sp_remoteoption with no parameters to see options."
	*/
	exec sp_getmessage 17774, @msg output
	print @msg
	return (1)
end

/*
**  If more than one option like @optname, show the duplicates and return.
*/
if @optcount > 1
begin
	/*
	** 17775, "Remote login option is not unique."
	*/
	exec sp_getmessage 17775, @msg output
	print @msg

	if @sptlang = 0
	    select duplicate_option = name
		from master.dbo.spt_values
			where name like "%" + @optname + "%"
				and type = "F"
				and number in (1, 1)
				and number > 0
	else
	    select duplicate_option = name, convert(char(22), description)
		from master.dbo.spt_values, master.dbo.sysmessages
			where 
				(name like "%" + @optname + "%" 
				or description like "%" + @optname + "%")
				and type = "F"
				and number in (1, 1)
				and number > 0
				and error between 17070 and 17079
				and msgnum = error
				and langid = @sptlang

	return (1)
end

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_remoteoption"
	return (1)
end

/*
**  Get the number which is the bit value to set
*/
if @whichone = 0
    select @statvalue = number
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%" and type = "F"
			and number in (1, 1)
			and number > 0
else
    select @statvalue = number
 	   from master.dbo.spt_values, master.dbo.sysmessages
		where description like "%" + @optname + "%" 
			and type = "F"
			and number in (1, 1)
			and number > 0
			and error between 17070 and 17079
			and msgnum = error
			and langid = @sptlang

/*
**  Now update sysremotelogins.
*/
if lower(@optvalue) in ("true", @true)
begin
	update master.dbo.sysremotelogins
		set status = status | @statvalue
		from master.dbo.sysremotelogins r, master.dbo.sysservers s
			where r.remoteserverid = s.srvid
				and s.srvname = @remoteserver
				and r.remoteusername = @remotename
				and r.suid = @suid
	/*
	** 17777, "Option '%1!' turned on."
	*/
	exec sp_getmessage 17777, @msg output
	print @msg, @optname
	return (0)

end

/*
**  We want to turn it off.
*/
else
begin
	update master.dbo.sysremotelogins
		set status = status & ~@statvalue
		from master.dbo.sysremotelogins r, master.dbo.sysservers s
			where r.remoteserverid = s.srvid
				and s.srvname = @remoteserver
				and r.remoteusername = @remotename
				and r.suid = @suid
	/*
	** 17778, "Option '%1!' turned off."
	*/
	exec sp_getmessage 17778, @msg output
	print @msg, @optname
	return (0)
end

return (0)
go
exec sp_procxmode 'sp_remoteoption', 'anymode'
go
grant execute on sp_remoteoption to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_rename')
begin
	drop procedure sp_rename
end
go
print "Installing sp_rename"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/password */

/*
** Messages for "sp_rename"             17780
**
** 17260, "Can't run %1! from within a transaction."
** 17460, "Object must be in the current database."
** 17240, "'%1!' is not a valid name."
** 17780, "There is already a column named '%1!' in table '%2!'."
** 17781, "Column name has been changed."
** 17782, "You do not own a table or column (or index) of that name in the current database."
** 17783, "There is already an index named '%1!' for table '%2!'."
** 17784, "Index name has been changed."
** 17785, "Table or view names beginning with '#' are not allowed."
** 17786, "Object name cannot be changed either because it does not exist in this database, or you don't own it, or it is a system name."
** 17787, "Newname already exists in systypes."
** 17788, "Newname already exists in sysobjects."
** 17789, "Object name has been changed."
** 18058, "Name of user-defined type name changed."
** 18071, "Set curwrite to the level of table/column."
** 18077, "Set curwrite to the level of index."
** 18078, "Set curwrite to the level of the object in systypes."
** 18079, "Set curwrite to the level of the object in sysobjects."
** 18080, "Certified state of object '%1!' has been set to 'Suspect'"
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_rename
@objname varchar(61),			/* old (current) object name */
@newname sysname(30)			/* new name we want to call it */
as

declare @objid int			/* object id of the thing to rename */
declare @msg varchar(250)


/*
** Running sp_rename inside a transaction would endanger the
** recoverability of the transaction/database. Disallow it.
*/

if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_rename"
	return (1)
end

set chained off
set transaction isolation level 1


if @objname like "%.%.%"
begin
	/*
	** 17460, "Object must be in the current database."
	*/
	exec sp_getmessage 17460, @msg output
	print @msg
	return (1)
end

/*
**  Check to see that the @newname is valid.
*/
if valid_name(@newname) = 0
begin
	/*
	** 17240, "'%1!' is not a valid name."
	*/
	exec sp_getmessage 17240, @msg output
	print @msg, @newname
	return (1)
end

/*
**  Check to see if we are renaming a table/column (or table/index)
**  or a table or usertype.
**  If @objname is of the form table.column then it's a column.
**  In the column case, we need to extract and verify the table and
**  column names and make sure the user owns the table that is getting
**  the rule bound.
*/
if @objname like "%.%"
begin
	declare @tabname varchar(30)		/* name of table */
	declare @colname varchar(30)		/* name of column */
	declare @colid tinyint			/* colid of the column */

	/*
	**  Get the table name out.
	*/
	select @tabname = substring(@objname, 1, charindex(".", @objname) - 1)
	select @colname = substring(@objname, charindex(".", @objname) + 1, 61)

	/*
	**  Now check to see that the column exists in a table owned
	**  by the user.
	*/


	select @objid = syscolumns.id, @colid = syscolumns.colid

		from sysobjects, syscolumns
	where syscolumns.id = sysobjects.id
		and sysobjects.name = @tabname
		and syscolumns.name = @colname
		and (sysobjects.sysstat & 7 = 2		/* user table */
		or sysobjects.sysstat & 7 = 3)		/* view */
		and sysobjects.uid = user_id()


	/*
	**  Did we find it?  If not, it might be an index name so we'll
	**  check in the next case.
	*/
	if @objid is not  null
	begin
		/*
		**  Check to make sure that there is no already a column
		**  that has the new name.
		*/
		if exists (select *
				from syscolumns
					where id = @objid
						and name = @newname)
		begin
			/*
			** 17780, "There is already a column named '%1!' in table '%2!'."
			*/
			exec sp_getmessage 17780, @msg output
			print @msg, @newname, @tabname
			return (1)
		end


		/*
		**  Go ahead and change the column name.
		*/
		update syscolumns
			set name = @newname
				from syscolumns
			where id = @objid
				and colid = @colid
		/*
		** If we are renaming the SYB_IDENTITY_COL
		** then turn off the COL_AUTO_IDENTITY bit (0x2).
		** Note that we can never rename a column to
		** SYB_IDENTIY_COL (since valid_name() will fail)
		** so don't worry about the converse.
		*/
		if (@colname = "SYB_IDENTITY_COL")
		begin
			update syscolumns
				set status = (~2 & status)
					from syscolumns
				where id = @objid
					and colid = @colid
		end

		/*
		** 17781, "Column name has been changed."
		*/
		exec sp_getmessage 17781, @msg output
		print @msg
		return (0)
	end

	/*
	**  Might be an index name.
	*/
	else
	begin


		select @objid = sysindexes.id, @colid = sysindexes.indid

			from sysobjects, sysindexes
		where sysindexes.id = sysobjects.id
			and sysobjects.name = @tabname
			and sysindexes.name = @colname
			and sysindexes.indid != 0
			and sysobjects.sysstat & 7 = 3	/* user table */
			and sysobjects.uid = user_id()

		/*
		**  If @objid is still NULL then that means it isn't an
		**  index name.  We checked above to see if it was a column
		**  name so now it's time to give up.
		*/
		if @objid is null
		begin
			/*
			** 17782, "You do not own a table or column (or index) of that name in the current database."
			*/
			exec sp_getmessage 17782, @msg output
			print @msg
			return (1)
		end

		/*
		**  Check to make sure that there is no already an index
		**  that has the new name.
		*/
		if exists (select *
				from sysindexes
					where id = @objid
						and name = @newname)
		begin
			/*
			** 17783, "There is already an index named '%1!' for table '%2!'."
			*/
			exec sp_getmessage 17783, @msg output
			print @msg, @newname, @tabname
			return (1)
		end


		/*
		**  Go ahead and change the index name.
		*/
		update sysindexes
			set name = @newname
				from sysindexes
			where id = @objid
				and indid = @colid


		/*
		** 17784, "Index name has been changed."
		*/
		exec sp_getmessage 17784, @msg output
		print @msg
		return (0)
	end
end

/*
**  Check to see if the object exists and is owned by the user.
**  It will either be in the sysobjects table or the systypes table.
**  Check sysobjects first.
**  System objects have ids < 100 and we don't allow their names to change.
*/
if exists (select id
	from sysobjects
		where id = object_id(@objname)
			and uid = user_id()
			and id > 99)
/*
**  Don't allow the newname to begin with #.
*/
begin
	if substring(@newname, 1, 1) = "#"
	begin
		/*
		** 17785, "Table or view names beginning with '#' are not allowed."
		*/
		exec sp_getmessage 17785, @msg output
		print @msg   
		return (1)
	end

end

/*
**  It's not in sysobjects so check systypes.
*/
else
begin


	select @objid = usertype

		from systypes
			where name = @objname
				and uid = user_id()
				and usertype > 99

	/*
	**  It's nowhere to be found so quit.
	*/
	if @objid is NULL
	begin
		/*
		** 17786, "Object name cannot be changed either because it does not exist in this database, or you don't own it, or it is a system name."
		*/
		exec sp_getmessage 17786, @msg output
		print @msg
		return (1)
	end


	/* Check that newname doesn't already exist. */
	if exists (select *
			from systypes
				where name = @newname)
	begin
		/*
		** 17787, "Newname already exists in systypes."
		*/
		exec sp_getmessage 17787, @msg output
		print @msg
		return (1)
	end


	/*
	** Change the name of a datatype
	*/
	update systypes
		set name = @newname
			where usertype = @objid

	/*
	** 18058, "Name of user-defined type name changed."
	*/
	exec sp_getmessage 18058, @msg output
	print @msg
	return (0)
end

/*
**  It might be a table so update the index entry for the table IF it has
**  no clustered index.  No clustered index means that there is an entry
**  for the table under the @objid with indid = 0.
*/
begin transaction

	/* Check that newname doesn't already exist. */
	if exists (select *
			from sysobjects
				where name = @newname
				and uid = user_id())
	begin
		/*
		** 17788, "Newname already exists in sysobjects."
		*/
		exec sp_getmessage 17788, @msg output
		print @msg
		rollback transaction
		return (1)
	end


	update sysobjects
		set name = @newname
			where id = object_id(@objname)

 
	 /*
	 **  This might not do anything -- only if we are dealing with a
	 **  table that has no clustered index.
	 **  Also change the name of the text entry, if any.
	 */
	 update sysindexes
		set name = @newname
			where id = object_id(@objname)
				and indid = 0

	 update sysindexes
		set name = "t" + @newname
			where id = object_id(@objname)
				and indid = 255

	 /*
 	 **	We also must update the object name in the descriptor
 	 **	otherwise, in the cache, the object would be under the
 	 **	old name.
 	 */
 	 dbcc chgobjname(@objname, @newname)

commit transaction

/*
** 17789, "Object name has been changed."
*/
exec sp_getmessage 17789, @msg output
print @msg


return (0)
go
exec sp_procxmode 'sp_rename', 'anymode'
go
grant execute on sp_rename to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_renamedb')
begin
	drop procedure sp_renamedb
end
go
print "Installing sp_renamedb"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/renamedb */

/*
** Messages for "sp_renamedb"           17790
**
** 17260, "Can't run %1! from within a transaction." 
** 17590, "The specified database does not exist."
** 17240, "'%1!' is not a valid name."
** 17791, "A database with the new name already exists."
** 17792, "The databases master, model, tempdb, sybsecurity and sybsystemprocs cannot be renamed."
** 17793, "System Administrator (SA) must set database '%1!' to single-user mode with sp_dboption before using sp_renamedb."
** 17794, "Database is renamed and in single-user mode."
** 17795, "System Administrator (SA) must reset it to multi-user mode with sp_dboption."
*/


/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function db_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_renamedb
@dbname sysname(30),			/* old (current) db name */
@newname sysname(30)			/* new name we want to call it */
as

declare @msg varchar(250)
declare @bitdesc varchar(30)		/* bit description for the db */

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_renamedb"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

/*
**  Make sure the database exists.
*/
if not exists (select *
		from master.dbo.sysdatabases
			where name = @dbname)
begin
	/*
	** 17590, "The specified database does not exist."
	*/
	exec sp_getmessage 17590, @msg output
	print @msg
	return (1)
end

/*
**  Make sure that the @newname db doesn't already exist.
*/
if exists (select *
		from master.dbo.sysdatabases
			where name = @newname)
begin
	/*
	** 17791, "A database with the new name already exists."
	*/
	exec sp_getmessage 17791, @msg output
	print @msg
	return (1)
end

/*
**  Check to see that the @newname is valid.
*/
if valid_name(@newname) = 0
begin
	/*
	** 17240, "'%1!' is not a valid name."
	*/
	exec sp_getmessage 17240, @msg output
	print @msg, @newname
	return (1)
end

/*
**  Don't allow the names of master, tempdb, and model to be changed.
*/
if @dbname in ("master", "model", "tempdb", "sybsecurity", "sybsystemprocs")
begin
	/*
	** 17792, "The databases master, model, tempdb, sybsecurity and sybsystemprocs cannot be renamed."
	*/
	exec sp_getmessage 17792, @msg output
	print @msg
	return (1)
end


/* 
** Check single user bit (4096) 
** Database must be in single user mode to necessitate the rid update in the
** database's DBTABLE
*/ 
select @bitdesc = null 
select @bitdesc = v.name
        from master.dbo.spt_values v, master.dbo.sysdatabases d 
                where d.dbid = db_id(@dbname) 
                        and v.type = "D" 
                        and d.status & v.number = 4096 
if @bitdesc is null 
begin 
	/*
	** 17793, "System Administrator (SA) must set database '%1!' to single-user mode with sp_dboption before using sp_renamedb."
	*/
	exec sp_getmessage 17793, @msg output
	print @msg, @dbname
        return(1)  
end  

/*
**  Update the dbinfo in the sysindexes row for syslogs of the database
**  whose name is being changed. Also the dbtable structure for the db
**  in question is updated with the new name.
**
**  NOTE: the following dbcc command relies on the above commands executing.
**	  Using this command outside of this procedure can cause a host of
**  	  perfidious problems.
*/
dbcc chgdbname (@dbname, @newname)

if @@error != 0
        return(1)

/*
**  Everything is ok so do it.
*/

update master.dbo.sysdatabases
	set name = @newname
		where name = @dbname

/* Restore old db name if the update fails (e.g. no space left in log). */
if @@error != 0
begin
        dbcc chgdbname (@newname, @dbname)
        return(1)
end

/*
** 17794, "Database is renamed and in single-user mode."
*/
exec sp_getmessage 17794, @msg output
print @msg

/*
** 17795, "System Administrator (SA) must reset it to multi-user mode with sp_dboption."
*/
exec sp_getmessage 17795, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_renamedb', 'anymode'
go
grant execute on sp_renamedb to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_serveroption')
begin
	drop procedure sp_serveroption
end
go
print "Installing sp_serveroption"
go

/* Sccsid = "%M% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */

/*
** Messages for "sp_serveroption"       17800
**
** 17260, "Can't run %1! from within a transaction." 
** 17800, "No such server -- run sp_helpserver to list servers."
** 17801, "Usage: sp_serveroption [server, optname, {true | false}]"
** 17802, "Server option doesn't exist or can't be set by user."
** 17803, "Run sp_serveroption with no parameters to see options."
** 17804, "Server option is not unique."
** 17806, "Option can be set for remote servers only -- not the local server."
** 17807, "Settable server options."
** 17431, "true"
** 17432, "false"
*/

create procedure sp_serveroption
@server varchar(30) = NULL,		/* server name to change */
@optname varchar(20) = NULL,		/* option name to turn on/off */
@optvalue varchar(10) = NULL		/* true or false */
as

declare @srvid int			/* id of the server */
declare @statvalue smallint		/* number of option */
declare @optcount int			/* number of options like @optname */
declare @msg varchar(250) 
declare @true varchar(10) 
declare @false varchar(10) 

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  If no @server given, just list the possible server options.
**  Only certain status bits may be set or cleared.  
**  The default is to allow timeouts (bit 0 is clear) and to
**  perform no network password encryption (bit 1 is clear).
**	   settable                	    not settable
**      ------------------------------  --------------------------
**	  timeouts (0)
**	  net password encryption (1)
*/
if @server is null
begin
	/* 17807, "Settable server options." */
	exec sp_getmessage 17807, @msg out
	print @msg
	select "" = name
		from master.dbo.spt_values
			where type = "A"
				and number not in (-1, 1)
		order by name
	return (0)
end

/*
**  Verify the server name and get the @srvid
*/
select @srvid = srvid
	from master.dbo.sysservers
		where srvname = @server

/*
**  If @server not found, say so. 
*/
if @srvid is NULL
begin
	/*
	** 17800, "No such server -- run sp_helpserver to list servers."
	*/
	exec sp_getmessage 17800, @msg output
	print @msg
	return (1)
end

/*
**  Check remaining parameters.
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
/* 17432, "false" */
exec sp_getmessage 17432, @false out
if @optname is NULL or lower(@optvalue) not in 
	("true", "false", @true, @false) or @optvalue is null
begin
	/*
	** 17801, "Usage: sp_serveroption [server, optname, {true | false}]"
	*/
	exec sp_getmessage 17801, @msg output
	print @msg
	return (1)
end

/*
**  Use @optname and try to find the right option.
**  If there isn't just one, print appropriate diagnostics and return.
*/
select @optcount = count(*)
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%" and type = "A"
			and number not in (-1, 1)

/*
**  If no option, show the user what the options are.
*/
if @optcount = 0
begin
	/*
	** 17802, "Server option doesn't exist or can't be set by user."
	*/
	exec sp_getmessage 17802, @msg output
	print @msg
	/*
	** 17803, "Run sp_serveroption with no parameters to see options."
	*/
	exec sp_getmessage 17803, @msg output
	print @msg
	return (1)
end

/*
**  If more than one option like @optname, show the duplicates and return.
*/
if @optcount > 1
begin
	/*
	** 17804, "Server option is not unique."
	*/
	exec sp_getmessage 17804, @msg output
	print @msg

	select duplicate_option = name
		from master.dbo.spt_values
			where name like "%" + @optname + "%"
				and type = "A"
				and number not in (-1, 1)

	return (1)
end

/*
**  Currently there are two options that can be set -- no timeouts and
**  net password encryption -- and both only apply to remote servers.  
**  If the current server is local then reject it.
*/
if @srvid = 0
begin
	/*
	** 17806, "Option can be set for remote servers only -- not the local server."
	*/
	exec sp_getmessage 17806, @msg output
	print @msg
	return (1)
end


/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/* 
	** 17260, "Can't run %1! from within a transaction." 
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_serveroption"
	return (1)
end
/*
**  Get the number which is the bit value to set
*/
select @statvalue = number
 	   from master.dbo.spt_values
		where name like "%" + @optname + "%" and type = "A"
			and number > 0

/*
** Check role -- "timeouts" requires SA role while 
** "net password encryption" requires SSO role.
*/

/* 
** check "timeouts" and "no timeouts" 
*/
if @statvalue = 0 or @statvalue = 1
begin
	if (proc_role("sa_role") != 1)
		return(1)
end

/* 
** check "net password encryption"
*/
if @statvalue = 2
begin
	if (proc_role("sso_role") != 1)
		return(1)
end

/*
**  Now update sysservers.
**  The timeouts option is handled a little strangely since the default
**  is timeouts.  Therefore timeouts = true means to clear the bit
**  and timeouts = false means to set the bit.
*/
if lower(@optvalue) in ("true", @true)
begin
	if @statvalue = 1
	begin
		update master.dbo.sysservers
			set srvstatus = srvstatus & ~@statvalue
				where srvid = @srvid
	end
	else
	begin
		update master.dbo.sysservers
			set srvstatus = srvstatus | @statvalue
				where srvid = @srvid
	end
end

/*
**  We want to turn it off.
*/
else
begin
	if @statvalue = 1
	begin
		update master.dbo.sysservers
			set srvstatus = srvstatus | @statvalue
				where srvid = @srvid
	end
	else
	begin
		update master.dbo.sysservers
			set srvstatus = srvstatus & ~@statvalue
				where srvid = @srvid
	end
end

return (0)
go
exec sp_procxmode 'sp_serveroption', 'anymode'
go
grant execute on sp_serveroption to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_serverinfo')
begin
	drop procedure sp_serverinfo
end
go
print "Installing sp_serverinfo"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_serverinfo"         17796
**
** 17796, "Legal request codes are as follows:"
*/

create procedure sp_serverinfo
@request	varchar(30) = NULL,
@arg1		varchar(30) = NULL,	/* optional arg1 */
@arg2		varchar(30) = NULL,	/* optional arg2 */
@arg3		varchar(30) = NULL,	/* optional arg3 */
@arg4		varchar(30) = NULL,	/* optional arg4 */
@arg5		varchar(30) = NULL,	/* optional arg5 */
@arg6		varchar(30) = NULL,	/* optional arg6 */
@arg7		varchar(30) = NULL,	/* optional arg7 */
@arg8		varchar(30) = NULL,	/* optional arg8 */
@arg9		varchar(30) = NULL	/* optional arg9 */
as

declare @csid		int		/* character set id */
declare @soid		int		/* sort order id */
declare @msg            varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

if (@request is null  or  @request = "help")
begin
	/*
	** 17796, "Legal request codes are as follows:"
	*/
	exec sp_getmessage 17796, @msg output
	print @msg
	print "    server_csname"
	print "    server_soname"
	print "    csdefinition"
	print "    sodefinition"
	return (9)
end

if (@request = "server_csname")
    begin
	/*
	** User wants the name of the server's default character set.
	** No additional arguments required.
	*/
	select @csid = value
	from master.dbo.syscurconfigs
	where config = 131

	select name
	from master.dbo.syscharsets
	where id = @csid and type between 1000 and 1999

	return (0)
    end
else if (@request = "server_soname")
    begin
	/*
	** User wants the name of the server's default sort order.
	** No additional arguments required.
	*/
	select @soid = value
	from master.dbo.syscurconfigs
	where config = 123

	select @csid = value
	from master.dbo.syscurconfigs
	where config = 131

	select name
	from master.dbo.syscharsets
	where id = @soid and csid = @csid and type between 2000 and 2999

	return (0)
    end
else if (@request = "csdefinition")
    begin
	/*
	** User wants the type, id, and definition (IMAGE field) of the
	** character set specified in "@arg1".
	*/
	select @csid = id
	from master.dbo.syscharsets
	where name = @arg1

	set textsize 32768

	select type, id, definition
	from master.dbo.syscharsets
	where id = @csid and type between 1000 and 1999

	return (0)
    end
else if (@request = "sodefinition")
    begin
	/*
	** User wants the name of the server's character set.
	** No additional arguments required.
	*/
	/*
	** User wants the definition (IMAGE field) of the sort order which
	** is the logical equivalent to the server's default sort order,
	** except based on the character set specified in "@arg1".
	*/
	select @soid = value
	from master.dbo.syscurconfigs
	where config = 123

	select @csid = id
	from master.dbo.syscharsets
	where name = @arg1 and type between 1000 and 1999

	select definition
	from master.dbo.syscharsets
	where id = @soid and csid = @csid and type between 2000 and 2999

	return (0)
    end
else
    begin
	/*
	** Unknown request code.
	*/
	return (1)
    end
go
exec sp_procxmode 'sp_serverinfo', 'anymode'
go
grant execute on sp_serverinfo to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_server_info')
begin
	drop procedure sp_server_info
end
go
print "Installing sp_server_info"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_server_info"
**
** 18043, "Attribute id %1! is not supported."
*/

create procedure sp_server_info
@attribute_id int = NULL		/* optional attribute id */
as

declare @msg varchar(250)

set nocount on

/* If an attribute id was specified then just return the info for that
** attribute.
*/
if @attribute_id is not null
begin
	/* Verify that the attribute is valid. */
	if not exists ( select attribute_id 
		from sybsystemprocs.dbo.spt_server_info
			where attribute_id = @attribute_id )
	begin
		/*
		** 18059, "Attribute id %1! is not supported."
		*/
		exec sp_getmessage 18059, @msg output
		print @msg, @attribute_id
		return (1)
	end

	select * from sybsystemprocs.dbo.spt_server_info
		where attribute_id = @attribute_id
end

/* If no attribute was specified then return info for all supported
** attributes.
*/
else
begin
	select * from sybsystemprocs.dbo.spt_server_info
end

return (0)
go
exec sp_procxmode 'sp_server_info', 'anymode'
go
grant execute on sp_server_info to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_inform')
begin
	drop procedure sp_inform
end
go
print "Installing sp_inform"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** A Microsoft catalog stored procedure is named sp_server_info, too
** close to the Sybase internal stored proc "sp_serverinfo".  Since
** Sybase's sp_serverinfo has not been documented to customers, this new
** stored procedure simply calls sp_serverinfo.  This new procedure
** should replace sp_serverinfo eventually in Sybase products and could
** be exposed to customers at any time.
*/

create procedure sp_inform
@request	varchar(30) = NULL,
@arg1		varchar(30) = NULL,	/* optional arg1 */
@arg2		varchar(30) = NULL,	/* optional arg2 */
@arg3		varchar(30) = NULL,	/* optional arg3 */
@arg4		varchar(30) = NULL,	/* optional arg4 */
@arg5		varchar(30) = NULL,	/* optional arg5 */
@arg6		varchar(30) = NULL,	/* optional arg6 */
@arg7		varchar(30) = NULL,	/* optional arg7 */
@arg8		varchar(30) = NULL,	/* optional arg8 */
@arg9		varchar(30) = NULL	/* optional arg9 */
as

declare @re_request	varchar(30)
declare @re_arg1	varchar(30)
declare @re_arg2	varchar(30)
declare @re_arg3	varchar(30)
declare @re_arg4	varchar(30)
declare @re_arg5	varchar(30)
declare @re_arg6	varchar(30)
declare @re_arg7	varchar(30)
declare @re_arg8	varchar(30)
declare @re_arg9	varchar(30)
declare @retval		int

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

select @re_request = @request
select @re_arg1 = @arg1
select @re_arg2 = @arg2
select @re_arg3 = @arg3
select @re_arg4 = @arg4
select @re_arg5 = @arg5
select @re_arg6 = @arg6
select @re_arg7 = @arg7
select @re_arg8 = @arg8
select @re_arg9 = @arg9
select @retval = 1

execute @retval = sp_serverinfo @request = @re_request, 
	@arg1 = @re_arg1, @arg2 = @re_arg2, @arg3 = @re_arg3, 
	@arg4 = @re_arg4, @arg5 = @re_arg5, @arg6 = @re_arg6, 
	@arg7 = @re_arg7, @arg8 = @re_arg8, @arg9 = @re_arg9

return @retval
go
exec sp_procxmode 'sp_inform', 'anymode'
go
grant execute on sp_inform to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setreplicate')
begin
	drop procedure sp_setreplicate
end
go
print "Installing sp_setreplicate"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*
** Messages for "sp_setreplicate"	17960
**
** 17230, "Only the System Administrator (SA) or the Database Owner
**	   (dbo) may execute this stored procedure."
** 17431, "true"
** 17432, "false"
** 17460, "Object must be in the current database."
** 17461, "Object does not exist in this database."
** 17961, "Usage: sp_setreplicate object_name, {true | false}"
** 17962, "The replication status for '%1!' is already set to %2!.
**	   Replication status for '%3!' does not change."
** 17963, "An object with the same name, but owned by a different user
**	   is already being replicated.  The object '%1!' cannot be
**	   replicated."
** 17964, "The replication status for '%1!' is set to %2!."
** 17965, "The replication status for '%1!' is currently %2!."
** 17966, "Due to system failure, the replication status for '%1!' has
**	   not been changed."
** 17967, "Only the System Administrator (SA), the Database Owner (dbo) or
**	   a user with REPLICATION authorization may execute this stored
**	   procedure."
*/
create procedure sp_setreplicate
@replicate_name	varchar(92) = NULL,	/* obj we want to mark as replicate */
@setflag 	varchar(5) = NULL	/* set or unset the replicate status. */
as

declare @current_status	smallint /* current sysstat value for the object. */
declare @new_status	smallint /* new sysstat value for the object. */
declare @rep_constant 	smallint /* bit which indicates a replicated object. */
declare @dbccbit	int	 /* The "on"/"off" bit for the DBCC command */
declare @db		varchar(30) 	/* db of object. */
declare @owner		varchar(30) 	/* owner of object. */
declare @object		varchar(30)	/* object's name. */
declare @true		varchar(10)
declare @false		varchar(10)
declare @msg 		varchar(200)
declare @tmpstr		varchar(10)
declare @sptlang	int
declare @procval	int

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
** Replication enabled flag is 8000H (which is -32768D)
*/
select @rep_constant = -32768

/*
** Initialize 'true' and 'false' strings
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
/* 17432, "false" */
exec sp_getmessage 17432, @false out

/*
** Set 'sptlang' for proper printing of object information.  Used mainly
** for the 'select' statement which is executed when we are invoked with
** no parameters.  Copied from similar code in 'sp_help'
*/
select @sptlang = @@langid
if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17100 and 17109
		and langid = @@langid)
	    select @sptlang = 0
end

/*
** If we are invoked with no parameters, then just print out all objects
** which are marked for replication.  The 'select' statement is heavily
** based upon the one found in 'sp_help'.
*/
if (@replicate_name is NULL and @setflag is NULL)
begin
	select
		Name = o.name,
		Type = convert(char(16), m.description + x.name)
	from
		sysobjects o,
		master.dbo.spt_values v,
		master.dbo.spt_values x,
		master.dbo.sysmessages m
	where 
		o.sysstat & 2055 = v.number
		and v.type = "O"
		and v.msgnum = m.error
		and isnull(m.langid, 0) = @sptlang
		and m.error between 17100 and 17109
		and x.type = "R"
		and o.userstat & -32768 = x.number
		and (o.sysstat & @rep_constant) = @rep_constant

	return (0)
end

/*
** Crack the name into its corresponding pieces.
*/
execute sp_namecrack 	@replicate_name, 
			@db = @db output, 
			@owner = @owner output,
			@object = @object output

/*
** Make sure that the object is in the current database.
*/
if (@db is not NULL and @db != db_name())
begin
	/*
	** 17460, "Object must be in the current database."
	*/
        exec sp_getmessage 17460, @msg output
        print @msg
	return (1)
end

/*
**  Make sure that the object actually exists.
*/
if (object_id(@replicate_name) is NULL)
begin
	/*
	** 17461, "Object does not exist in this database."
	*/
	exec sp_getmessage 17461, @msg output
	print @msg
	return (1)
end

/*
** If the 'setflag' parameter is NULL, then we are only interested in the
** current replication status of the specified object.
*/
if (@setflag is NULL)
begin
	select
		@current_status = sysstat
	from 
		sysobjects holdlock
	where 
		id = object_id(@replicate_name)

	if (@current_status & @rep_constant) = @rep_constant
	begin
		select @tmpstr = @true
	end
	else
	begin
		select @tmpstr = @false
	end

	/*
	** 17965 "The replication status for '%1!' is currently %2!."
	*/
	exec sp_getmessage 17965, @msg output
	print @msg, @replicate_name, @tmpstr

	return (0)
end

/*
** You must be SA, dbo or have REPLICATION role to execute this
** sproc.
*/
if (user_id() = 1)
begin
	/*
	** If we have SA role, then we may not be the "real"
	** database owner and may have assumed the identity of the
	** database owner through our SA role privileges.  If
	** this is the case, we should audit an SA role success
	** to audit the fact that SA role privileges were needed
	** to run these commands.
	*/
	if charindex("sa_role", show_role()) > 0
	begin
		select @procval = proc_role("sa_role")
	end
end
else
begin
	if (proc_role("sa_role") != 1)
	begin
		/*
		** 17967, "Only the System Administrator (SA), the
		**	   Database Owner (dbo) or a user with REPLICATION
		**	   authorization may execute this stored
		**	   procedure."
		*/
		exec sp_getmessage 17967, @msg output
		print @msg
		return (1)
	end
end

/*
** Check for a valid setname parameter
*/
if (lower(@setflag) not in ("true", "false", @true, @false))
begin
	/*
	** 17961 "Usage: sp_setreplicate object_name, {true | false}"
	*/
	exec sp_getmessage 17961, @msg output
	print @msg
	return (1)
end

/*
** Get the object's current status. Hold a read lock on sysobjects so that 
**	the status cannot be changed until we're done.
*/
select @current_status = sysstat 
	from sysobjects holdlock
		where id = object_id(@replicate_name)

/*
** Perform the requested operation on the object.
*/
if lower(@setflag) in ("false", @false)
begin
	/*
	** Is the replicate status bit even set?
	*/
	if (@current_status & @rep_constant) = 0
	begin
		/*
		** 17962 "The replication status for '%1!' is already
		**	  set to %2!.  Replication status for '%3!'
		**	  does not change."
		*/
		exec sp_getmessage 17962, @msg output
		print @msg, @replicate_name, @setflag, @replicate_name
		return(1)
	end

	select @new_status = @current_status & ~@rep_constant
	select @dbccbit = 0
end
else
begin
	/*
	** Is the replicate status bit already set?
	*/
	if (@current_status & @rep_constant) != 0
	begin
		/*
		** 17962 "The replication status for '%1!' is already
		**	  set to %2!.  Replication status for '%3!'
		**	  does not change."
		*/
		exec sp_getmessage 17962, @msg output
		print @msg, @replicate_name, @setflag, @replicate_name
		return(1)
	end

	/*
	** Make sure that no like object with the same name, but a
	** different owner, exists.  We need to do this because
	** the SQL Server does not send owner information along
	** with the object to the Replication Server.  This
	** restriction may be lifted in future versions.
	*/
	if exists (select * from sysobjects
			where name = @object
			and (
				(type = "U ") /* user table */
			or
				(type = "P ") /* stored procedure */
			)
			and sysstat & @rep_constant != 0)
	begin
		/*
		** 17963 "An object with the same name, but owned by a
		**	  different user is already being replicated.
		**	  The object '%1!' cannot be replicated."
		*/
		exec sp_getmessage 17963, @msg output
		print @msg, @replicate_name
		return(1)
	end

	select @new_status = @current_status | @rep_constant
	select @dbccbit = 1
end

/*
** Update the object's sysstat column
*/
begin transaction

	update sysobjects
		set sysstat = @new_status
			where id = object_id(@replicate_name)

	/*
	** Update the object's status in cache.
	*/
	dbcc setreplicate(@replicate_name, @dbccbit)

	if @@error != 0
	begin
		/*
		** 17966 "Due to system failure, the replication status
		**	  for '%1!' has not been changed."
		*/
		exec sp_getmessage 17966, @msg output
		print @msg, @replicate_name, @setflag

		rollback transaction

		return (1)
	end

commit transaction

/*
** 17964 "The replication status for '%1!' is set to %2!."
*/
exec sp_getmessage 17964, @msg output
print @msg, @replicate_name, @setflag
return(0)
go
exec sp_procxmode 'sp_setreplicate', 'anymode'
go
grant execute on sp_setreplicate to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_spaceused')
begin
	drop procedure sp_spaceused
end
go
print "Installing sp_spaceused"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/spaceused */
 
/*
** Messages for "sp_spaceused"          17830
**
** 17460, "Object must be in the current database." 
** 17461, "Object does not exist in this database."
** 17830, "Object is stored in 'sysprocedures' and
** 	   has no space allocated directly."
** 17831, "Views don't have space allocated."
** 17832, "Not avail."
*/

/*
** IMPORTANT NOTE:
** This stored procedure uses the built-in function object_id() in the
** where clause of a select query. If you intend to change this query
** or use the object_id() or db_id() builtin in this procedure, please read the
** READ.ME file in the $DBMS/generic/sproc directory to ensure that the rules
** pertaining to object-id's and db-id's outlined there, are followed.
*/

create procedure sp_spaceused
@objname varchar(92) = null,		/* the object we want size on */
@list_indices int = 0			/* don't sum all indices, list each */
as

declare @type	smallint		/* the object type */
declare @msg	varchar(250)		/* message output */
declare @dbname varchar(30)             /* database name */
declare @tabname varchar(30)            /* table name */
declare @length	int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
**  Check to see that the objname is local.
*/
if @objname is not null
begin
	/*
        ** Get the dbname and ensure that the object is in the
        ** current database. Also get the table name - this is later
        ** needed to see if information is being requested for syslogs.
        */
        execute sp_namecrack @objname,
                             @db = @dbname output,
                             @object = @tabname output
        if @dbname is not NULL
	begin
		/*
		** 17460, "Object must be in the current database." 
		*/
		if (@dbname != db_name())
		begin
			exec sp_getmessage 17460, @msg output
			print @msg
			return (1)
		end
	end

	/*
	**  Does the object exist?
	*/
	if not exists (select *
                        from sysobjects
                                where id = object_id(@objname))
	begin
		/*
		** 17461, "Object does not exist in this database."
		*/
		exec sp_getmessage 17461, @msg output
	        print @msg
		return (1)
	end

	/* Get the object type */
        select @type = sysstat & 7
                from sysobjects
                        where id = object_id(@objname)
	/*
	**  See if it's a space object.
	**  types are:
	**	0 - trigger
	**	1 - system table
	**	2 - view
	**	3 - user table
	**	4 - sproc
	**	6 - default
	**	7 - rule
	*/
	if not exists (select *
			from sysindexes
				where id = object_id(@objname)
					and indid < 2)
	begin
		if @type in (0, 4, 6, 7)
		begin
			/*
			** 17830, "Object is stored in 'sysprocedures' and
			** 	   has no space allocated directly."
			*/
			exec sp_getmessage 17830, @msg output
		        print @msg
			return (1)
		end

		if @type = 2
		begin
			/*
			** 17831, "Views don't have space allocated."
			*/
			exec sp_getmessage 17831, @msg output
		        print @msg
			return (1)
		end
	end

end

/*
**  If @objname is null, then we want summary data.
*/
set nocount on
if @objname is null
begin
	declare @slog_res_pgs numeric(20,9),  	/* number of reserved pgs. in syslogs */
		@slog_dpgs numeric(20,9) 	/* number of data pages in syslogs */
	
	select distinct database_name = db_name(), database_size =
		ltrim(str(sum(size) / (1048576 / d.low), 10 ,1)) + " MB"
		from master.dbo.sysusages, master.dbo.spt_values d
			where dbid = db_id()
				and d.number = 1
				and d.type = "E"
			having dbid = db_id()
				and d.number = 1
				and d.type = "E"

	/*
	** Obtain the page count for syslogs table. 
	** 
	** The syslogs system table has only data (no index does exist).
	** Built-in functions reserved_pgs(8, doampg) and data_pgs(8, doampg) 
	** will always return the same value.  This is due to the fact that
	** syslogs pages are allocated an extent worth at a time and all log
	** pages in this extent are set as in use.  This is why we aren't able 
	** to determine the amount of unused syslogs pages by simply doing
	** reserved_pgs - data_pgs.
	**
	** Also note that syslogs table doesn't have OAM pages.  However,
	** builtin functions reserved_pgs() and data_pgs() handle syslogs
	** as a special case.
	*/
	declare @doampg int
	select @doampg = doampg from sysindexes where id = 8
	select @slog_res_pgs = convert(numeric(20,9),reserved_pgs(8, @doampg)),
	       @slog_dpgs = convert(numeric(20,9),data_pgs(8, @doampg))

	/*
	** Obtain the page count for all the objects in the current
	** database; except for 'syslogs' (id = 8). Store the results
	** in a temp. table (#pgcounts).
	**
	** Note that we first retrieve the needed information from
	** sysindexes and we only then apply the OAM builtin system
	** functions on that data.  The reason being we want to relax
	** keeping the sh_int table lock on sysindexes for the duration
	** of the command.
	*/
	select distinct
		s.name,
		s.id,
		res_pgs = 0,
		low = d.low,
		dpgs = convert(numeric(20,9), s.doampg),
		ipgs = convert(numeric(20,9), s.ioampg),
		unused = convert(numeric(20,9), 0)
	into #pgcounts 
	from sysindexes s, master.dbo.spt_values d
		where s.id != 8
			and d.number = 1 
			and d.type = "E" 
		having d.number = 1
			and d.type = "E"
	
	update #pgcounts set
		res_pgs = reserved_pgs(id,dpgs)+reserved_pgs(id,ipgs),
		dpgs = convert(numeric(20,9),data_pgs(id,dpgs)),
		ipgs = convert(numeric(20,9),data_pgs(id,ipgs)),
		unused = convert(numeric(20,9),
			  (reserved_pgs(id,dpgs)+reserved_pgs(id,ipgs)) -
			     (data_pgs(id,dpgs)+data_pgs(id,ipgs)))

	/*
	** Compute the summary results by adding page counts from
	** individual data objects. Add to the count the count of 
	** pages for 'syslogs'.  Convert the total pages to space
	** used in Kilo bytes.
	*/
	select distinct reserved = convert(char(15), convert(varchar(11),
		convert(numeric(11,0), (sum(res_pgs) + @slog_res_pgs) *
			(low / 1024))) + " " + "KB"),
		data = convert(char(15), convert(varchar(11),
			convert(numeric(11,0), (sum(dpgs) + @slog_dpgs) *
			(low / 1024))) + " " + "KB"),
		index_size = convert(char(15), convert(varchar(11),
			convert(numeric(11,0),  sum(ipgs) * (low / 1024)))
			+ " " + "KB"),
		unused = convert(char(15), convert(varchar(11),
			convert(numeric(11,0), sum(unused) * (low / 1024)))
			+ " " + "KB")
	from #pgcounts
end

/*
**  We want a particular object.
*/
else
begin
	if (@tabname = "syslogs") /* syslogs */
	begin
		/*
		** 17832, "Not avail."
		*/
		exec sp_getmessage 17832, @msg output

		select @length = max(datalength(o.name))
		    from sysobjects o, sysindexes i
			where i.id = object_id(@objname)
				and o.id = object_id(@objname)

		if (@length > 20)
		    select name = o.name,
			rowtotal = convert(char(11), @msg),
			reserved = convert(char(15), convert(varchar(11),
				convert(numeric(11,0), convert(numeric(20,9),
				reserved_pgs(i.id, i.doampg) * (d.low / 1024))))
				+ " " + "KB"),
			data = convert(char(15), convert(varchar(11),
			        convert(numeric(11,0), convert(numeric(20,9),
				data_pgs(i.id, i.doampg) * (d.low / 1024))))
				+ " " + "KB"),
			index_size = convert(char(15), convert(varchar(11), 0) 
			        + " " + "KB"),
			unused = convert(char(11), @msg)
			from sysobjects o, sysindexes i,
			     master.dbo.spt_values d
				where i.id = object_id(@objname)
					and o.id = object_id(@objname)
					and d.number = 1
					and d.type = "E"
		else
		    select name = convert(char(20), o.name),
			rowtotal = convert(char(10), @msg),
			reserved = convert(char(15), convert(varchar(11),
				convert(numeric(11,0), convert(numeric(20,9),
				reserved_pgs(i.id, i.doampg) * (d.low / 1024))))
				+ " " + "KB"),
			data = convert(char(15), convert(varchar(11),
			        convert(numeric(11,0), convert(numeric(20,9),
				data_pgs(i.id, i.doampg) * (d.low / 1024)))) 
				+ " " + "KB"),
			index_size = convert(char(15), convert(varchar(11), 0) 
			        + " " + "KB"),
			unused = convert(char(11), @msg)
			from sysobjects o, sysindexes i,
			     master.dbo.spt_values d
				where i.id = object_id(@objname)
					and o.id = object_id(@objname)
					and d.number = 1
					and d.type = "E"
	end
	else
	begin
		select  name = o.name,
			iname = i.name, 
			low = d.low,
			rowtotal = rowcnt(i.doampg),
			reserved = convert(numeric(20,9),
				(reserved_pgs(i.id, i.doampg) +
				reserved_pgs(i.id, i.ioampg))),
			data = convert(numeric(20,9),data_pgs(i.id, i.doampg)),
			index_size =  convert(numeric(20,9),
				data_pgs(i.id, i.ioampg)),
			unused = convert(numeric(20,9), 
				((reserved_pgs(i.id, i.doampg) +
			   	reserved_pgs(i.id, i.ioampg)) -
			   	(data_pgs(i.id, i.doampg) +
			     	data_pgs(i.id, i.ioampg))))
		into #pagecounts
		from sysobjects o, sysindexes i, master.dbo.spt_values d
				where i.id = object_id(@objname)
					and o.id = object_id(@objname)
					and d.number = 1
					and d.type = "E"

	    if (@list_indices = 1)
	    begin
		select @length = max(datalength(iname))
			from #pagecounts
		if (@length > 20)
	        	select  index_name = iname,
				size = convert(char(10), convert(varchar(11),
		    	       	       convert(numeric(11,0),
							index_size / 1024 *
			        			low)) + " " + "KB"),
		    		reserved = convert(char(10), 
					   convert(varchar(11),
		    	       	   	   convert(numeric(11,0),
						   reserved / 1024 * 
			       			   low)) + " " + "KB"),
		    		unused = convert(char(10), convert(varchar(11),
		    		 	 convert(numeric(11,0), unused / 1024 *
							low)) + " " + "KB")
	        	from #pagecounts
		else
			select  index_name = convert(char(20), iname),
				size = convert(char(10), convert(varchar(11),
		    	       	       convert(numeric(11,0),
							index_size / 1024 *
			        			low)) + " " + "KB"),
		    		reserved = convert(char(10), 
					   convert(varchar(11),
		    	       	   	   convert(numeric(11,0),
						   reserved / 1024 * 
			       			   low)) + " " + "KB"),
		    		unused = convert(char(10), convert(varchar(11),
		    		 	 convert(numeric(11,0), unused / 1024 *
							low)) + " " + "KB")
	        	from #pagecounts

	    end

	    select @length = max(datalength(name))
		from #pagecounts

	    if (@length > 20)
	        select distinct name,
		    rowtotal = convert(char(11), sum(rowtotal)),
		    reserved = convert(char(15), convert(varchar(11),
		    	       convert(numeric(11,0), sum(reserved) *
			       (low / 1024))) + " " + "KB"),
		    data = convert(char(15), convert(varchar(11),
		    	       convert(numeric(11,0), sum(data) * (low / 1024)))
			       + " " + "KB"),
		    index_size = convert(char(15), convert(varchar(11),
		    		convert(numeric(11,0), sum(index_size) *
				(low / 1024))) + " " + "KB"),
		    unused = convert(char(15), convert(varchar(11),
		    		convert(numeric(11,0), sum(unused) *
				(low / 1024))) + " " + "KB")
	        from #pagecounts
	    else
	        select distinct name = convert(char(20), name),
		    rowtotal = convert(char(11), sum(rowtotal)),
		    reserved = convert(char(15), convert(varchar(11),
		    	       convert(numeric(11,0), sum(reserved) *
			       (low / 1024))) + " " + "KB"),
		    data = convert(char(15), convert(varchar(11),
		    	       convert(numeric(11,0), sum(data) * (low / 1024)))
			       + " " + "KB"),
		    index_size = convert(char(15), convert(varchar(11),
		    		convert(numeric(11,0), sum(index_size) *
				(low / 1024))) + " " + "KB"),
		    unused = convert(char(15), convert(varchar(11),
		    		convert(numeric(11,0), sum(unused) *
				(low / 1024))) + " " + "KB")
	        from #pagecounts
	end
end
return (0)
go
go
exec sp_procxmode 'sp_spaceused', 'anymode'
go
grant execute on sp_spaceused to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sproc_columns')
begin
	drop procedure sp_sproc_columns
end
go
print "Installing sp_sproc_columns"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_sproc_columns"
**
** 18039, "Table qualifier must be name of current database"
*/

create procedure sp_sproc_columns
@procedure_name		varchar(36) = '%', 	/* name of stored procedure  */
@procedure_owner 	varchar(32) = null,	/* owner of stored procedure */
@procedure_qualifier	varchar(32) = null,	/* name of current database  */
@column_name		varchar(32) = null	/* col name or param name    */
as

declare @msg			varchar(250)
declare @group_num		int
declare @semi_position		int
declare @full_procedure_name	char(70)
declare @procedure_id		int

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* If column name not supplied, match all */
if @column_name is null 
	select @column_name = '%'

/* The qualifier must be the name of current database or null */
if @procedure_qualifier is not null
begin
	if db_name() != @procedure_qualifier
	begin
	if @procedure_qualifier = ''
		begin
			/* in this case, we need to return an empty result 
			** set because the user has requested a database with
			** an empty name
			*/
			select @procedure_name = ''
			select @procedure_owner = ''
		end
		else
		begin
			/*
			** 18039, Table qualifier must be name of current database
			*/
			exec sp_getmessage 18039, @msg output
			print @msg
			return
		end
	end
end


/* first we need to extract the procedure group number, if one exists */
select @semi_position = charindex(';',@procedure_name)
if (@semi_position > 0)
begin	/* If group number separator (;) found */
	select @group_num = convert(int,substring(@procedure_name, 
						  @semi_position + 1, 2))
	select @procedure_name = substring(@procedure_name, 1, 
					   @semi_position -1)
end
else
begin	/* No group separator, so default to group number of 1 */
	select @group_num = 1
end

if @procedure_owner is null
begin	/* If unqualified procedure name */
	select @full_procedure_name = @procedure_name
end
else
begin	/* Qualified procedure name */
	select @full_procedure_name = @procedure_owner + '.' + @procedure_name
end

/*	Get Object ID */
select @procedure_id = object_id(@full_procedure_name)

if ((charindex('%',@full_procedure_name) = 0) and
	(charindex('_',@full_procedure_name) = 0)  and
	@procedure_id != 0)
begin
/*
** this block is for the case where there is no pattern
** matching required for the table name
** With the current data in the spt_datatype_info table, the convert() below
** is never being used.
** These conversions were ported from the original Microsoft INSTCAT.SQL
** file which contained catalog stored procedures for 4.9 and earlier SQL
** Servers.
*/
	select	/* INTn, FLOATn, DATETIMEn and MONEYn types */
		procedure_qualifier = db_name(),
		procedure_owner = user_name(o.uid),
		procedure_name = o.name +';'+ ltrim(str(c.number,5)),
		column_name = c.name,
		column_type = convert(smallint, 0),
		data_type = d.data_type
			    +convert(smallint, 
				     isnull(d.aux,
					    ascii(substring("666AAA@@@CB??GG",
						            2*(d.ss_dtype%35+1)
							    +2-8/c.length,
							    1)) - 60)),
		type_name = rtrim(substring(d.type_name,
					1+isnull(d.aux,
					     ascii(substring("III<<<MMMI<<A<A",
							2*(d.ss_dtype%35+1)
							+2-8/c.length,
						        1)) - 60), 
					    13)),
		"precision"= isnull(d.data_precision, convert(int,c.length))
			     +isnull(d.aux, convert(int,
					     ascii(substring("???AAAFFFCKFOLS",
						          2*(d.ss_dtype%35+1)
							  +2-8/c.length,1))
							  -60)),
		length = isnull(d.length, convert(int,c.length))
			 +convert(int, isnull(d.aux,
					     ascii(substring("AAA<BB<DDDHJSPP",
						    	     2*(d.ss_dtype%35
							     +1)+2-8/c.length,
						             1))-64)),
		scale = d.numeric_scale +convert(smallint,
					   isnull(d.aux,
					     ascii(substring("<<<<<<<<<<<<<<?",
						        2*(d.ss_dtype%35+1)
							+2-8/c.length,
						        1))-60)),
		radix = d.numeric_radix,
		nullable =	/* set nullability from status flag */
			convert(smallint, convert(bit, c.status&8)),
		remarks = convert(varchar(254),null),	/* Remarks are NULL */
		ss_data_type = c.type,
		colid = c.colid
	from
		syscolumns c,
		sysobjects o,
		sybsystemprocs.dbo.spt_datatype_info d,
		systypes t,
		sysprocedures p
	where
		o.id = @procedure_id
		and c.id = o.id
		and c.type = d.ss_dtype
		and c.name like @column_name
		and d.ss_dtype in (111, 109, 38, 110)	/* Just *N types */
		and c.number = @group_num

	union
	select
		procedure_qualifier = db_name(),
		procedure_owner = user_name(o.uid),
		procedure_name = o.name +';'+ ltrim(str(@group_num,5)),
		column_name = 'RETURN_VALUE',
		column_type = convert(smallint, 5), /* return parameter */
		data_type = d.data_type+convert(smallint,
					  isnull(d.aux,
					     ascii(substring("666AAA@@@CB??GG",
						          2*(d.ss_dtype%35+1)
							  +2-8/d.length,1))
						          -60)),
		type_name = d.type_name,
		"precision"= isnull(d.data_precision, convert(int,d.length))
			     +isnull(d.aux, convert(int,
					     ascii(substring("???AAAFFFCKFOLS",
						          2*(d.ss_dtype%35+1)
							  +2-8/d.length,1))
							  -60)),
		length = isnull(d.length, convert(int,t.length))
			 +convert(int, isnull(d.aux,
					     ascii(substring("AAA<BB<DDDHJSPP",
						    	     2*(d.ss_dtype%35
							     +1)+2-8/t.length,
						             1))-64)),
		scale = d.numeric_scale +convert(smallint,
					   isnull(d.aux,
					     ascii(substring("<<<<<<<<<<<<<<?",
						        2*(d.ss_dtype%35+1)
							+2-8/d.length,
						        1))-60)),
		radix = d.numeric_radix,
		nullable = convert(smallint, 0),
		remarks = convert(varchar(254),null),	/* Remarks are NULL */
		ss_data_type = d.ss_dtype,
		colid = convert(tinyint, 0) /* first row returned */
	from
		sysobjects o,
		sybsystemprocs.dbo.spt_datatype_info d,
		systypes t
	where
		o.id = @procedure_id
		and d.ss_dtype = 56  /* int for return code */
		and t.type = 56
	union
	select		   /* All other types including user data types */
		procedure_qualifier = db_name(),
		procedure_owner = user_name(o.uid),
		procedure_name = o.name +';'+ ltrim(str(c.number,5)),
		column_name = c.name,
		column_type = convert(smallint, 0),

		/*   Map systypes.type to ODBC type	       		*/
		/*   SS-Type "				 1	      "	*/
		/*	     "33 3 3 4 44 5 5 2 5 55666"	        */
		/*	     "45 7 9	5 78 0 2 2 6 89012"             */
		data_type = convert(smallint,
			       ascii(substring("8;<9<H<<<<<:<=6<5<A<?<@<GC?GD",
						t.type%34+1,1))-60),
		type_name = t.name,
		"precision"= isnull(d.data_precision, convert(int,c.length))
			     +isnull(d.aux, convert(int,
					     ascii(substring("???AAAFFFCKFOLS",
						       2*(d.ss_dtype%35+1)
						       +2-8/c.length,1))
						       -60)),
		length = isnull(d.length, convert(int,c.length))
			 +convert(int, isnull(d.aux,
					     ascii(substring("AAA<BB<DDDHJSPP",
						             2*(d.ss_dtype%35
							     +1)+2-8/c.length,
						             1))-64)),
		scale = d.numeric_scale +convert(smallint,
					  isnull(d.aux,
					    ascii(substring("<<<<<<<<<<<<<<?",
							    2*(d.ss_dtype%35+1)
							    +2-8/c.length,
							    1))-60)),
		radix = d.numeric_radix,

		/* set nullability from status flag */
		nullable = convert(smallint, convert(bit, c.status&8)),
		remarks = convert(varchar(254),null),	/* Remarks are NULL */
		ss_data_type = c.type,
		colid = c.colid
	from
		syscolumns c,
		sysobjects o,
		sybsystemprocs.dbo.spt_datatype_info d,
		systypes t
	where
		o.id = @procedure_id
		and c.id = o.id
		and c.type = d.ss_dtype
		and c.usertype *= t.usertype
		and c.name like @column_name
		and c.number = @group_num
		and d.ss_dtype not in (111, 109, 38, 110) /* No *N types */

	 order by colid
end
else
begin
	/* 
	** this block is for the case where there IS pattern
	** matching done on the table name
	** With the current data in the spt_datatype_info table, the convert() 
	** below is never being used.
	** These conversions were ported from the original Microsoft INSTCAT.SQL
	** file which contained catalog stored procedures for 4.9 and earlier 
	** SQL Servers.
	*/
	if @procedure_owner is null
		select @procedure_owner = '%'

	select	/* INTn, FLOATn, DATETIMEn and MONEYn types */
		procedure_qualifier = db_name(),
		procedure_owner = user_name(o.uid),
		procedure_name = o.name +';'+ ltrim(str(c.number,5)),
		column_name = c.name,
		column_type = convert(smallint, 0),
		data_type = d.data_type+convert(smallint,
					  isnull(d.aux,
					     ascii(substring("666AAA@@@CB??GG",
						          2*(d.ss_dtype%35+1)
							  +2-8/c.length,1))
						          -60)),
		type_name = rtrim(substring(d.type_name,
				    1+isnull(d.aux,
					     ascii(substring("III<<<MMMI<<A<A",
					                  2*(d.ss_dtype%35+1)
							  +2-8/c.length,
						          1))-60), 13)),
		"precision"= isnull(d.data_precision, convert(int,c.length))
			     +isnull(d.aux, convert(int,
					     ascii(substring("???AAAFFFCKFOLS",
						           2*(d.ss_dtype%35+1)
							   +2-8/c.length,1))
						           -60)),
		length = isnull(d.length, convert(int,c.length))
			 +convert(int, isnull(d.aux,
					     ascii(substring("AAA<BB<DDDHJSPP",
							   2*(d.ss_dtype%35+1)
							   +2-8/c.length,
							   1))-64)),
		scale = d.numeric_scale +convert(smallint,
					    isnull(d.aux,
					     ascii(substring("<<<<<<<<<<<<<<?",
							   2*(d.ss_dtype%35+1)
							   +2-8/c.length,
							   1))-60)),
		radix = d.numeric_radix,
		/* set nullability from status flag */
		nullable = convert(smallint, convert(bit, c.status&8)),
		remarks = convert(varchar(254),null),	/* Remarks are NULL */
		ss_data_type = c.type,
		colid = c.colid
	from
		syscolumns c,
		sysobjects o,
		sybsystemprocs.dbo.spt_datatype_info d,
		systypes t
	where
		o.name like @procedure_name
		and user_name(o.uid) like @procedure_owner
		and o.id = c.id
		and c.type = d.ss_dtype
		and c.name like @column_name
		and o.type = 'P'			/* Just Procedures */
		and d.ss_dtype in (111, 109, 38, 110)	/* Just *N types */

	union
	select distinct
		procedure_qualifier = db_name(),
		procedure_owner = user_name(o.uid),
		procedure_name = o.name +';'+ ltrim(str(p.number,5)),
		column_name = 'RETURN_VALUE',
		column_type = convert(smallint, 5), /* return parameter */
		data_type = d.data_type+convert(smallint,
					  isnull(d.aux,
					     ascii(substring("666AAA@@@CB??GG",
						          2*(d.ss_dtype%35+1)
							  +2-8/d.length,1))
						          -60)),
		type_name = d.type_name,
		"precision"= isnull(d.data_precision, convert(int,d.length))
			     +isnull(d.aux, convert(int,
					     ascii(substring("???AAAFFFCKFOLS",
						          2*(d.ss_dtype%35+1)
							  +2-8/d.length,1))
							  -60)),
		length = isnull(d.length, convert(int,t.length))
			 +convert(int, isnull(d.aux,
					     ascii(substring("AAA<BB<DDDHJSPP",
						    	     2*(d.ss_dtype%35
							     +1)+2-8/t.length,
						             1))-64)),
		scale = d.numeric_scale +convert(smallint,
					   isnull(d.aux,
					     ascii(substring("<<<<<<<<<<<<<<?",
						        2*(d.ss_dtype%35+1)
							+2-8/d.length,
						        1))-60)),
		radix = d.numeric_radix,
		nullable = convert(smallint, 0),
		remarks = convert(varchar(254),null),	/* Remarks are NULL */
		ss_data_type = d.ss_dtype,
		colid = convert(tinyint, 0) /* first row returned */
	from
		sysobjects o,
		sybsystemprocs.dbo.spt_datatype_info d,
		systypes t,
		sysprocedures p
	where
		o.name like @procedure_name
		and user_name(o.uid) like @procedure_owner
		and d.ss_dtype = 56  /* int for return code */
		and t.type = 56
		and o.type = 'P'			/* Just Procedures */
		and p.id = o.id
		and 'RETURN_VALUE' like @column_name
	union
	select		   /* All other types including user data types */
		procedure_qualifier = db_name(),
		procedure_owner = user_name(o.uid),
		procedure_name = o.name +';'+ ltrim(str(c.number,5)),
		column_name = c.name,
		column_type = convert(smallint, 0),
		/*   Map systypes.type to ODBC type    			*/
		/*   SS-Type  "				 1	      " */
		/*	      "33 3 3 4 44 5 5 2 5 55666"		*/
		/*	      "45 7 9 5 78 0 2 2 6 89012"    		*/
		data_type = convert(smallint,
			       ascii(substring("8;<9<H<<<<<:<=6<5<A<?<@<GC?GD",
					       t.type%34+1,1))-60),
		type_name = t.name,
		"precision"= isnull(d.data_precision, convert(int,c.length))
			     +isnull(d.aux, 
				     convert(int,
					     ascii(substring("???AAAFFFCKFOLS",
					                   2*(d.ss_dtype%35+1)
							   +2-8/c.length,1))
					           -60)),
		length = isnull(d.length, convert(int,c.length))
			 +convert(int,
				  isnull(d.aux,
					 ascii(substring("AAA<BB<DDDHJSPP",
					                 2*(d.ss_dtype%35+1)
							 +2-8/c.length,
					                 1))-64)),
		scale = d.numeric_scale
			+convert(smallint,
				 isnull(d.aux,
					ascii(substring("<<<<<<<<<<<<<<?",
					                2*(d.ss_dtype%35+1)
							+2-8/c.length,
					                1))-60)),
		radix = d.numeric_radix,
		/* set nullability from status flag */
		nullable = convert(smallint, convert(bit, c.status&8)),
		remarks = convert(varchar(254),null),	/* Remarks are NULL */
		ss_data_type = c.type,
		colid = c.colid
	from
		syscolumns c,
		sysobjects o,
		sybsystemprocs.dbo.spt_datatype_info d,
		systypes t
	where
		o.name like @procedure_name
		and user_name(o.uid) like @procedure_owner
		and o.id = c.id
		and c.type = d.ss_dtype
		and c.usertype *= t.usertype
		and o.type = 'P' 			  /* Just Procedures */
		and c.name like @column_name
		and d.ss_dtype not in (111, 109, 38, 110) /* No *N types */

	order by procedure_owner, procedure_name, colid
end
go



go
exec sp_procxmode 'sp_sproc_columns', 'anymode'
go
grant execute on sp_sproc_columns to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_statistics')
begin
	drop procedure sp_statistics
end
go
print "Installing sp_statistics"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_statistics"          18039
**
** 18039, "Table qualifier must be name of current database."
** 18040, "Catalog procedure '%1!' can not be run in a transaction.
**
*/

/*
** Sp_statistics returns statistics for the given table, passed as first 
** argument. A row is returned for the table and then for each index found
** in sysindexes, starting with lowest value index id in sysindexes and 
** proceeding through the highest value index.  
**
** Returned rows consist of the columns:
** table qualifier (database name), table owner, table name from sysobjects, 
** non_unique (0/1), index qualifier (same as table name), 
** index name from sysindexes, type (SQL_INDEX_CLUSTERED/SQL_INDEX_OTHER), 
** sequence in index, column name, collation (currently, this is always "A"), 
** table cardinality (row count), and number of pages used by table (doampg).
*/

create procedure sp_statistics (
	@table_name		varchar(32),
	@table_owner		varchar(32) = null,
	@table_qualifier	varchar(32) = null,
	@index_name		varchar(32) = '%',
	@is_unique 		char(1) = 'N')
as
declare @indid			int
declare @lastindid		int
declare @full_table_name	char(70)
declare @msg 			varchar(250)

/*
** Verify table qualifier is name of current database.
*/
if @table_qualifier is not null
begin
	if db_name() != @table_qualifier
	begin	/* If qualifier doesn't match current database */
		/*
		** 18039, "Table qualifier must be name of current database."
		*/
		exec sp_getmessage 18039, @msg output
		print @msg
		return (1)
	end
end

if @@trancount > 0
begin
	/*
	** 18040, "Catalog procedure '%1!' can not be run in a transaction.
	*/
	exec sp_getmessage 18040, @msg output
	print @msg, "sp_statistics"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

create table #TmpIndex(
	table_qualifier	varchar(32),
	table_owner	varchar(32),
	table_name	varchar(32),
	index_qualifier varchar(32) null,
	index_name	varchar(32) null,
	non_unique	smallint null,
	type		smallint,
	seq_in_index	smallint null,
	column_name	varchar(32) null,
	collation	char(1) null,
	index_id	int null,
	cardinality	int null,
	pages		int null,
	status		smallint)

/*
** Fully qualify table name.
*/
if @table_owner is null
begin	/* If unqualified table name */
	select @full_table_name = @table_name
end
else
begin	/* Qualified table name */
	select @full_table_name = @table_owner + '.' + @table_name
end

/*
** Start at lowest index id, while loop through indexes. 
** Create a row in #TmpIndex for every column in sysindexes, each is
** followed by an row in #TmpIndex with table statistics for the preceding
** index.
*/
select @indid = min(indid)
	from sysindexes
	where id = object_id(@full_table_name)
		and indid > 0
		and indid < 255

while @indid != NULL
begin
	insert #TmpIndex	/* Add all columns that are in index */
	select
		db_name(),		/* table_qualifier */
		user_name(o.uid),	/* table_owner	   */
		o.name,			/* table_name	   */
		o.name, 		/* index_qualifier */
		x.name,			/* index_name	   */
		0,			/* non_unique	   */
		1,			/* SQL_INDEX_CLUSTERED */
		colid,			/* seq_in_index	   */
		INDEX_COL(@full_table_name,indid,colid),/* column_name	   */
		"A",			/* collation	   */
		@indid,			/* index_id 	   */
		rowcnt(x.doampg),	/* cardinality	   */
		data_pgs(x.id,doampg),	/* pages	   */
		x.status		/* status	   */
	from sysindexes x, syscolumns c, sysobjects o
	where x.id = object_id(@full_table_name)
		and x.id = o.id
		and x.id = c.id
		and c.colid < keycnt+(x.status&16)/16
		and x.indid = @indid

	/*
	** Save last index and increase index id to next higher value.
	*/
	select @lastindid = @indid
	select @indid = NULL

	select @indid = min(indid)
	from sysindexes
	where id = object_id(@full_table_name)
		and indid > @lastindid
		and indid < 255
end

update #TmpIndex
	set non_unique = 1
	where status&2 != 2 /* If non-unique index */

update #TmpIndex
	set
		type = 3,		/* SQL_INDEX_OTHER */
		cardinality = NULL,
		pages = NULL
	where index_id > 1		/* If non-clustered index */

/* 
** Now add row with table statistics 
*/
insert #TmpIndex
	select
		db_name(),			/* table_qualifier */
		user_name(o.uid),		/* table_owner	   */
		o.name, 			/* table_name	   */
		null,				/* index_qualifier */
		null,				/* index_name	   */
		null,				/* non_unique	   */
		0,				/* SQL_table_STAT  */
		null,				/* seq_in_index	*/
		null,				/* column_name	   */
		null,				/* collation	   */
		0,				/* index_id 	   */
		rowcnt(x.doampg),		/* cardinality	   */
		data_pgs(x.id,doampg),		/* pages	   */
		0				/* status	   */
	from sysindexes x, sysobjects o
	where o.id = object_id(@full_table_name)
		and x.id = o.id
		and (x.indid = 0 or x.indid = 1)	
	/*  
	** If there are no indexes
	** then table stats are in a row with indid = 0
	*/

if @is_unique != 'Y'	
begin
	/* If all indexes desired */
	select
		table_qualifier,
		table_owner,
		table_name,
		non_unique,
		index_qualifier,
		index_name,
		type,
		seq_in_index,
		column_name,
		collation,
		cardinality,
		pages
	from #TmpIndex
	where index_name like @index_name 	/* If matching name */
		or index_name is null		/* If SQL_table_STAT row */
	order by non_unique, type, index_name, seq_in_index
end
else	
begin
	/* else only unique indexes desired */
	select
		table_qualifier,
		table_owner,
		table_name,
		non_unique,
		index_qualifier,
		index_name,
		type,
		seq_in_index,
		column_name,
		collation,
		cardinality,
		pages
	from #TmpIndex
	where (non_unique = 0 			/* If unique */
		or non_unique is NULL)		/* If SQL_table_STAT row */
		and (index_name like @index_name	/* If matching name */
		or index_name is NULL)		/* If SQL_table_STAT row */
	order by non_unique, type, index_name, seq_in_index

end

drop table #TmpIndex

return (0)
go
exec sp_procxmode 'sp_statistics', 'anymode'
go
grant execute on sp_statistics to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sendmsg')
begin
	drop procedure sp_sendmsg
end
go
print "Installing sp_sendmsg"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

create procedure sp_sendmsg 
@ip_address varchar(255),		/* IP address to send the message */
@port_number  int,			/* Port number */
@message varchar(255)			/* Message to be sent */
as

declare @returncode int

if @@trancount = 0
begin
	set chained off
	set transaction isolation level 1
end


/* Do the work */
select @returncode = syb_sendmsg(@ip_address, @port_number, @message)

if ((@returncode = 0) or (@returncode is null))
begin
	return(0)
end
else
begin
	return(1)
end

go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_stored_procedures')
begin
	drop procedure sp_stored_procedures
end
go
print "Installing sp_stored_procedures"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

/*
** Messages for "sp_stored_procedures"	18041
**
** 18041, "Stored Procedure qualifier must be name of current database."
**
*/
create procedure sp_stored_procedures
@sp_name	varchar(36) = null,	/* stored procedure name */
@sp_owner	varchar(32) = null,	/* stored procedure owner */
@sp_qualifier	varchar(32) = null	/* stored procedure qualifier; 
					** For the SQL Server, the only valid
					** values are NULL or the current 
					** database name
					*/
as

declare	@msg	varchar(90)

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* If qualifier is specified */
if @sp_qualifier is not null
begin
	/* If qualifier doesn't match current database */
	if db_name() != @sp_qualifier
	begin
		/* If qualifier is not specified */
		if @sp_qualifier = ''
		begin
			/* in this case, we need to return an empty 
			** result set because the user has requested a 
			** database with an empty name 
			*/
			select @sp_name = ''
			select @sp_owner = ''
		end

		/* qualifier is specified and does not match current database */
		else
		begin	
			/* 
			** 18041, "Stored Procedure qualifer must be name of
			** current database"
			*/
			exec sp_getmessage 18041, @msg out
			print @msg
			return (1)
		end
	end
end

/* If procedure name not supplied, match all */
if @sp_name is null
begin  
	select @sp_name = '%'
end
else 
begin
	/* If owner name is not supplied, but procedure name is */ 
	if (@sp_owner is null) and (charindex('%', @sp_name) = 0)
	begin
		/* If procedure exists and is owned by the current user */
		if exists (select * 
			   from sysobjects
			   where uid = user_id()
				and name = @sp_name
				and type = 'P') /* Object type of Procedure */
		begin
			/* Set owner name to current user */
			select @sp_owner = user_name()
		end
	end
end

/* If procedure owner not supplied, match all */
if @sp_owner is null	
	select @sp_owner = '%'

/* 
** Retrieve the stored procedures and associated info on them
*/
select procedure_qualifier = db_name(),
	procedure_owner = user_name(o.uid),
	procedure_name = o.name +';'+ ltrim(str(p.number,5)),
	num_input_params = -1,		/* Constant since value unknown */
	num_output_params = -1, 	/* Constant since value unknown */
	num_result_sets = -1,		/* Constant since value unknown */
	remarks = convert(varchar(254),null)	/* Remarks are NULL */
from sysobjects o,sysprocedures p,sysusers u
where o.name like @sp_name
	and p.sequence = 0
	and user_name(o.uid) like @sp_owner
	and o.type = 'P'		/* Object type of Procedure */
	and p.id = o.id
	and u.uid = user_id()		/* constrain sysusers uid for use in 
					** subquery 
					*/

	and (suser_id() = 1 		/* User is the System Administrator */
	     or  o.uid = user_id()	/* User created the object */
					/* here's the magic..select the highest 
					** precedence of permissions in the 
					** order (user,group,public)  
					*/

	     /*
	     ** The value of protecttype is
	     **
	     **		0  for grant with grant
	     **		1  for grant and,
	     **		2  for revoke
	     **
	     ** As protecttype is of type tinyint, protecttype/2 is
	     ** integer division and will yield 0 for both types of
	     ** grants and will yield 1 for revoke, i.e., when
	     ** the value of protecttype is 2.  The XOR (^) operation
	     ** will reverse the bits and thus (protecttype/2)^1 will
	     ** yield a value of 1 for grants and will yield a
	     ** value of zero for revoke.
	     **
	     ** Normal uids have values upto 16383, roles have uids
	     ** from 16384 upto 16389 and uids of groups start from
	     ** 16390 onwards.
	     **
	     ** If there are several entries in the sysprotects table
	     ** with the same Object ID, then the following expression
	     ** will prefer an individual uid entry over a group entry
	     ** and prefer a group entry over a role entry.
	     **
	     ** For example, let us say there are two users u1 and u2
	     ** with uids 4 and 5 respectiveley and both u1 and u2
	     ** belong to a group g12 whose uid is 16390.  procedure p1
	     ** is owned by user u0 and user u0 performs the following
	     ** actions:
	     **
	     **		grant exec on p1 to g12
	     **		revoke grant on p1 from u1
	     **
	     ** There will be two entries in sysprotects for the object
	     ** p1, one for the group g12 where protecttype = grant (1)
	     ** and one for u1 where protecttype = revoke (2).
	     **
	     ** For the group g12, the following expression will
	     ** evaluate to:
	     **
	     **		(((+)*abs(16390-16383))*2) + ((1/2)^1))
	     **		= ((14) + (0)^1) = 14 + 1 = 15
	     **
	     ** For the user entry u1, it will evaluate to:
	     **
	     **		(((+)*abs(4-16383)*2) + ((2/2)^1))
	     **		= ((abs(-16379)*2 + (1)^1)
	     **		= 16379*2 + 0 = 32758
	     **
	     ** As the expression evaluates to a bigger number for the
	     ** user entry u1, select max() will chose 32758 which,
	     ** ANDed with 1 gives 0, i.e., sp_stored_procedures will
	     ** not display this particular procedure to the user.
	     **
	     ** When the user u2 invokes sp_stored_procedures, there is
	     ** only one entry for u2, which is the entry for the group
	     ** g12, and so this entry will be selected thus allowing
	     ** the procedure in question to be displayed.
	     **
	     ** Notice that multiplying by 2 makes the number an
	     ** even number (meaning the last digit is 0) so what
	     ** matters at the end is (protecttype/2)^1.
	     **
	     ** NOTE: With fix 137148, uids have been extended into the
	     ** negative domain (-16383 <= uid <= +16383). For negative uids,
	     ** the above expression will yield a negative number as sign(-ve)
	     ** yields -1 and max() will not choose this negative number.
	     ** To ensure that the above expression returns a positive large
	     ** number, we now use power(sign(uid),2) instead of sign(uid).
	     */

	     or ((select max(((power(sign(uid),2)*abs(uid-16383))*2)
			     + ((protecttype/2)^1))
		   from sysprotects p
		   where p.id = o.id		
		   /*
		   ** get rows for public, current users, user's groups
		   */
		   and (p.uid = 0  		/* get rows for public */
		        or p.uid = user_id()	/* current user */
		        or p.uid = u.gid) 	/* users group */
			     
		   /*
		   ** check for SELECT, EXECUTE privilege.
		   */
	           and (action in (193,224))	/* check for SELECT,EXECUTE 
						** privilege 
						*/
		   )&1 			/* more magic...normalize GRANT */
	    	  ) = 1	 		/* final magic...compare Grants	*/
	    )
order by procedure_qualifier, procedure_owner, procedure_name
go
go
exec sp_procxmode 'sp_stored_procedures', 'anymode'
go
grant execute on sp_stored_procedures to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindefault')
begin
	drop procedure sp_unbindefault
end
go
print "Installing sp_unbindefault"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */
 
/*
** Messages for "sp_unbindefault"       17840
** 17840, "Column or usertype must be in 'current' database."
** 17841, "Default unbound from table column."
** 17842, "The specified column has no default."
** 17843, "You do not own a table with a column of that name."
** 17844, "You do not own a user datatype of that name."
** 17845, "The specified user datatype has no default."
** 17846, "Default unbound from datatype."
** 17847, "Columns of the user datatype specified had their defaults unbound."
** 17848, "You cannot unbind a declared default. Use ALTER TABLE command."
*/

create procedure sp_unbindefault
@objname varchar(61),			/* table/column or datatype name */
@futureonly varchar(15) = NULL		/* flag to indicate extent of binding */
as

declare @defid int			/* id of the default to unbind */
declare @futurevalue varchar(15)	/* the value of @futureonly that causes
					** the binding to be limited */
declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @futurevalue = "futureonly"	/* initialize @futurevalue */

/*
**  When a default or rule is bound to a user-defined datatype, it is also
**  bound, by default, to any columns of the user datatype that are currently
**  using the existing default or rule as their default or rule.  This default
**  action may be overridden by setting @futureonly = @futurevalue when the
**  procedure is invoked.  In this case existing columns with the user
**  datatype won't have their existing default or rule changed.
*/

/*
**  Check to see that the object names are local to the current database.
*/
if @objname like "%.%.%"
begin
	/*
	** 17840, "Column or usertype must be in 'current' database."
	*/
	exec sp_getmessage 17840, @msg output
	print @msg
	return (1)
end

/*
**  If @objname is of the form tab.col then we are unbinding a column.
**  Otherwise its a datatype.  In the column case, we need to extract
**  and verify the table and column names and make sure the user owns
**  the table that is getting the default unbound.
*/
if @objname like "%.%"
begin
	declare @tabname varchar(30)		/* name of table */
	declare @colname varchar(30)		/* name of column */

	/*
	**  Get the table name out.
	*/
	select @tabname = substring(@objname, 1, charindex(".", @objname) - 1)
	select @colname = substring(@objname, charindex(".", @objname) + 1, 61)

	/*
	**  Find it.
	*/
	select @defid = syscolumns.cdefault
		from syscolumns, sysobjects
		where syscolumns.id = object_id(@tabname)
			and syscolumns.name = @colname
			and sysobjects.id = object_id(@tabname)
			and uid = user_id()
			and sysobjects.sysstat & 7 = 3	/* user table */

	if @defid is NULL
	begin
		/*
		**  17843, "You do not own a table with a column of that name."
		*/
		exec sp_getmessage 17843, @msg output
        	print @msg
		return (1)
	end

	/*
	**  Is there something bound to it?
	*/
	if @defid = 0
	begin
		/*
		** 17842, "The specified column has no default."
		*/
		exec sp_getmessage 17842, @msg output
        	print @msg
		return (1)
	end
	/*
	** Check to see that the default is not of declared type
	*/

	if exists (select * from sysprocedures
			where id = @defid
			and sequence = 0
			and status & 4096 = 4096)
	begin
		/*
		** 17848, "You cannot unbind a declared default. Use ALTER TABLE command."
		*/
		exec sp_getmessage 17848, @msg output
		print @msg
		return (1)
	end
	
	/*
	**  Unbind it.
	*/
	update syscolumns
		set cdefault = 0
			from syscolumns, sysobjects
		where syscolumns.id = object_id(@tabname)
			and syscolumns.name = @colname
			and sysobjects.id = object_id(@tabname)
			and uid = user_id()
			and sysobjects.sysstat & 7 = 3

	/*
	**  Since binding a default is a schema change,
	**  update schema count
	**  for the object in the sysobjects table.
	*/
	update sysobjects
		set schemacnt = schemacnt + 1
			from sysobjects
				where id = object_id(@tabname)
					and uid = user_id()
                                                      and schema_inc(object_id(@tabname)) is NULL

	/*
	** 17841, "Default unbound from table column."
	*/
	exec sp_getmessage 17841, @msg output
	print @msg
	return (0)
end
else
begin
	/*
	**  We're unbinding to a user type.  In this case, the @objname
	**  is really the name of the user datatype.
	**  When we unbind to a user type, any existing columns get changed
	**  to the new binding unless their current binding is not equal
	**  to the current binding for the usertype or if they set the
	**  @futureonly parameter to @futurevalue.
	*/
	declare @olddefault int			/* current default for type */

	/*
	**  Get the current default for the datatype.
	*/
	select @olddefault = tdefault
		from systypes
	where name = @objname
		and uid = user_id()
		and usertype > 100

	if @olddefault is null
	begin
		/*
		** 17844, "You do not own a user datatype of that name."
		*/
		exec sp_getmessage 17844, @msg output
	        print @msg
		return (1)
	end

	if @olddefault = 0
	begin
		/*
		** 17845, "The specified user datatype has no default."
		*/
		exec sp_getmessage 17845, @msg output
	        print @msg
		return (1)
	end

	update systypes
		set tdefault = 0
			from systypes
		where name = @objname
			and uid = user_id()
			and usertype > 100

	/*
	** 17846, "Default unbound from datatype."
	*/
	exec sp_getmessage 17846, @msg output
        print @msg

	/*
	**  Now see if there are any columns with the usertype that
	**  need the new binding.
	*/
	if isnull(@futureonly, "") != @futurevalue
		and exists (select *
			from syscolumns, systypes
				where syscolumns.usertype = systypes.usertype
					and systypes.name = @objname
					and systypes.usertype > 100
					and systypes.uid = user_id()
					and syscolumns.cdefault = @olddefault)
	begin
		/*
		**  Update the table schema to indicate that something
		**  has changed in the table's schema.
		*/
		update sysobjects
			set schemacnt = schemacnt + 1
				from sysobjects, syscolumns, systypes
			where sysobjects.id = syscolumns.id
				and syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()
				and syscolumns.cdefault = @olddefault
                                and sysobjects.id in
                                        (select s.id from sysobjects s
                                        where schema_inc(s.id) is NULL)

		/*
		**  Update syscolumns with new binding.
		*/
		update syscolumns
			set cdefault = systypes.tdefault
				from syscolumns, systypes
			where syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()
				and syscolumns.cdefault = @olddefault

		/*
		** 17847, "Columns of the user datatype specified had
		** their defaults unbound."
		*/
		exec sp_getmessage 17847, @msg output
	        print @msg

	end
end

return (0)
go
exec sp_procxmode 'sp_unbindefault', 'anymode'
go
grant execute on sp_unbindefault to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindrule')
begin
	drop procedure sp_unbindrule
end
go
print "Installing sp_unbindrule"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */
 
/*
** Messages for "sp_unbindrule"         17850
**
** 17840, "Column or usertype must be in 'current' database."
** 17843, "You do not own a table with a column of that name."
** 17844, "You do not own a user datatype of that name." 
** 17850, "Rule unbound from table column."
** 17851, "The specified column has no rule."
** 17852, "The specified user datatype has no rule."
** 17853, "Rule unbound from datatype."
** 17854, "Columns of the user datatype specified had their rules unbound."
** 17855, "You cannot unbind a declared constraint. Use ALTER TABLE command."
*/

create procedure sp_unbindrule
@objname varchar(61),			/* table/column or datatype name */
@futureonly varchar(15) = NULL		/* flag to indicate extent of binding */
as

declare @tot_constr int			/* total number of constraints */
declare @colid tinyint			/* column id */
declare @futurevalue varchar(15)	/* the value of @futureonly that causes
					** the binding to be limited */
declare @msg varchar(250)


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @futurevalue = "futureonly"	/* initialize @futurevalue */

/*
**  When a default or rule is bound to a user-defined datatype, it is also
**  bound, by default, to any columns of the user datatype that are currently
**  using the existing default or rule as their default or rule.  This default
**  action may be overridden by setting @futureonly = @futurevalue when the
**  procedure is invoked.  In this case existing columns with the user
**  datatype won't have their existing default or rule changed.
*/

/*
**  Check to see that the object names are local to the current database.
*/
if @objname like "%.%.%"
begin
	/*
	** 17840, "Column or usertype must be in 'current' database."
	*/
	exec sp_getmessage 17840, @msg output
	print @msg
	return (1)
end

/*
**  If @objname is of the form tab.col then we are unbinding a column.
**  Otherwise its a datatype.  In the column case, we need to extract
**  and verify the table and column names and make sure the user owns
**  the table that is getting the default unbound.
*/
if @objname like "%.%"
begin
	declare @tabname varchar(30)		/* name of table */
	declare @colname varchar(30)		/* name of column */

	/*
	**  Get the table name out.
	*/
	select @tabname = substring(@objname, 1, charindex(".", @objname) - 1)
	select @colname = substring(@objname, charindex(".", @objname) + 1, 61)

	/*
	**  Find it.
	*/
	if not exists (select syscolumns.colid
		from syscolumns, sysobjects
		where syscolumns.id = object_id(@tabname)
			and syscolumns.name = @colname
			and sysobjects.id = object_id(@tabname)
			and uid = user_id()
			and sysobjects.sysstat & 7 = 3)      /* user table */

	begin
		/*
		** 17843, "You do not own a table with a column of that name."
		*/
		exec sp_getmessage 17843, @msg output
        	print @msg  
		return (1)
	end

	/*
	**  Is there something bound to it?
	*/
	if exists (select syscolumns.colid
                from syscolumns, sysobjects
                where syscolumns.id = object_id(@tabname)
                        and syscolumns.name = @colname
                        and sysobjects.id = object_id(@tabname)
                        and uid = user_id()
                        and sysobjects.sysstat & 7 = 3      /* user table */ 
			and syscolumns.domain = 0)
	begin
		/*
		** 17851, "The specified column has no rule."
		*/
		exec sp_getmessage 17851, @msg output
        	print @msg  
		return (1)
	end
	/*
	** Check to see that the rule is not of declared type
	*/

	if exists (select * from sysprocedures
			where id = (select syscolumns.domain
				    from syscolumns, sysobjects
				    where syscolumns.id = object_id(@tabname)
					and syscolumns.name = @colname
					and sysobjects.id = object_id(@tabname)
					and uid = user_id() 
					and sysobjects.sysstat & 7 = 3)
						/* user table */ 
			and sequence = 0
			and status & 4096 = 4096)
	begin
		/*
		** 17855, "You cannot unbind a declared constraint. Use ALTER TABLE command."
		*/
		exec sp_getmessage 17855, @msg output
		print @msg
		return (1)
	end
	
	/*
	** If the status of the column reflects having more than one rule,
	** check if there indeed is more than one rules. If there is more
	** reset the domain field w/ a new rule.
	*/

	select @colid = syscolumns.colid
                from syscolumns, sysobjects
                where syscolumns.id = object_id(@tabname)
                        and syscolumns.name = @colname
                        and sysobjects.id = object_id(@tabname)
                        and uid = user_id()
                        and sysobjects.sysstat & 7 = 3

	select @tot_constr = count(*)
	from sysconstraints
	where tableid = object_id(@tabname)
		and colid = @colid

	/*
	**  Unbind it.
	*/
	if @tot_constr > 1
	begin
		update syscolumns
			set domain = (select max(constrid)
					from sysconstraints
					where tableid = object_id(@tabname)
						and colid = @colid)
				from syscolumns, sysobjects
			where syscolumns.id = object_id(@tabname)
				and syscolumns.name = @colname
				and sysobjects.id = object_id(@tabname)
				and uid = user_id()
				and sysobjects.sysstat & 7 = 3
	end
	else if @tot_constr > 0
	begin
		update syscolumns
			set domain = (select max(constrid)
					from sysconstraints
					where tableid = object_id(@tabname)
						and colid = @colid),
				status = syscolumns.status & 239
				from syscolumns, sysobjects
			where syscolumns.id = object_id(@tabname)
				and syscolumns.name = @colname
				and sysobjects.id = object_id(@tabname)
				and uid = user_id()
				and sysobjects.sysstat & 7 = 3
	end
	else
	begin
		update syscolumns
			set domain = 0
				from syscolumns, sysobjects
			where syscolumns.id = object_id(@tabname)
				and syscolumns.name = @colname
				and sysobjects.id = object_id(@tabname)
				and uid = user_id()
				and sysobjects.sysstat & 7 = 3
	end

	/*
	**  Since binding a rule is a schema change,
	**  update schema count
	**  for the object in the sysobjects table.
	*/
	update sysobjects
		set schemacnt = schemacnt + 1
			from sysobjects
				where id = object_id(@tabname)
					and uid = user_id()
                                                      and schema_inc(object_id(@tabname)) is NULL

	/*
	** 17850, "Rule unbound from table column."
	*/
	exec sp_getmessage 17850, @msg output
        print @msg  
	return (0)
end
else
begin
	/*
	**  We're unbinding to a user type.  In this case, the @objname
	**  is really the name of the user datatype.
	**  When we unbind to a user type, any existing columns get changed
	**  to the new binding unless their current binding is not equal
	**  to the current binding for the usertype or if they set the
	**  @futureonly parameter to @futurevalue.
	*/
	declare @oldrule int			/* current rule for type */

	/*
	**  Get the current rule for the datatype.
	*/
	select @oldrule = domain
		from systypes
	where name = @objname
		and uid = user_id()
		and usertype > 100

	if @oldrule is null
	begin
		/*
		** 17844, "You do not own a user datatype of that name." 
		*/
		exec sp_getmessage 17844, @msg output
        	print @msg  
		return (1)
	end

	if @oldrule = 0
	begin
		/*
		** 17852, "The specified user datatype has no rule."
		*/
		exec sp_getmessage 17852, @msg output
        	print @msg  
		return (1)
	end

	update systypes
		set domain = 0
			from systypes
		where name = @objname
			and uid = user_id()
			and usertype > 100

	/*
	** 17853, "Rule unbound from datatype."
	*/
	exec sp_getmessage 17853, @msg output
        print @msg  

	/*
	**  Now see if there are any columns with the usertype that
	**  need the new binding.
	*/
	if isnull(@futureonly, "") != @futurevalue
		and exists (select *
			from syscolumns, systypes
				where syscolumns.usertype = systypes.usertype
					and systypes.name = @objname
					and systypes.usertype > 100
					and systypes.uid = user_id()
					and syscolumns.domain = @oldrule)
	begin
		/*
		**  Update the table schema to indicate that something
		**  has changed in the table's schema.
		*/
		update sysobjects
			set schemacnt = schemacnt + 1
				from sysobjects, syscolumns, systypes
			where sysobjects.id = syscolumns.id
				and syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()
				and syscolumns.domain = @oldrule
                                and sysobjects.id in
                                        (select s.id from sysobjects s
                                        where schema_inc(s.id) is NULL)

		/*
		**  Update syscolumns with new binding.
		*/
		update syscolumns
			set domain = systypes.domain
				from syscolumns, systypes
			where syscolumns.usertype = systypes.usertype
				and systypes.name = @objname
				and systypes.usertype > 100
				and systypes.uid = user_id()
				and syscolumns.domain = @oldrule

		/*
		** 17854, "Columns of the user datatype specified 
		** had their rules unbound."
		*/
		exec sp_getmessage 17854, @msg output
        	print @msg  

	end
end

return (0)

go
exec sp_procxmode 'sp_unbindrule', 'anymode'
go
grant execute on sp_unbindrule to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_who')
begin
	drop procedure sp_who
end
go
print "Installing sp_who"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/serveroption */

/*
** Messages for "sp_who"		17nnn
** 
** 17231, "No login with the specified name exists." 
*/

create procedure sp_who @loginame varchar(30) = NULL as

declare @low int
declare @high int
declare @spidlow int
declare @spidhigh int
declare @msg varchar(250)
declare @len1 int, @len2 int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

select @low = 0, @high = 32767, @spidlow = 0, @spidhigh = 32767

if @loginame is not NULL
begin
	select @low = suser_id(@loginame), @high = suser_id(@loginame)
	if @low is NULL
	begin
		if @loginame like "[0-9]%"
		begin
			select @spidlow = convert(int, @loginame),
			     @spidhigh = convert(int, @loginame),
			     @low = 0, @high = 32767
		end
		else
		begin
			/*
			** 17231, "No login with the specified name exists." 
			*/
			exec sp_getmessage 17231, @msg output
			print @msg
			return (1)
		end
	end
end

select @len1 = max(datalength(suser_name(suid))),
       @len2 = max(datalength(db_name(dbid)))
	from master..sysprocesses
	where suid >= @low and suid <= @high and
	      spid >= @spidlow and spid <= @spidhigh

if (@len1 > 12 or @len2 > 10)
    begin
	select spid,status,loginame=suser_name(suid),
	   hostname,blk=convert(char(5),blocked),
	   dbname=db_name(dbid),cmd
	from master..sysprocesses
	where suid >= @low and suid <= @high
	and spid >= @spidlow and spid <= @spidhigh
    end
else
    begin
	select spid,status,loginame=convert(char(12), suser_name(suid)),
	   hostname,blk=convert(char(5),blocked),
	   dbname=convert(char(10), db_name(dbid)),cmd
	from master..sysprocesses
	where suid >= @low and suid <= @high
	and spid >= @spidlow and spid <= @spidhigh
    end

return (0)

go
exec sp_procxmode 'sp_who', 'anymode'
go
grant execute on sp_who to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_procqmode')
begin
	drop procedure sp_procqmode
end
go
print "Installing sp_procqmode"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*
** Messages for "sp_procqmode" 
**
** 17460, "Object must be in the current database.
** 17461, "Object does not exist in this database."
** 18097, "Object must be a trigger, view or stored procedure."
**
*/

/*
**
** usage: sp_procqmode [ {objectname | null} [, detail]]
**
** Sp_procqmode provides information about subquery processing in
** triggers, views and stored procedures.  The information consists
** of:
**	1. The subquery processing style (either 'pre-System 11' or
**	   'System 11 or later').
**	2. Whether there are any subqueries present in the query
**	   which defines the object.
**	3. Whether there are any rows in the syscomments table for
**	   this object.
** Points 2 & 3 are only displayed if the 'detail' argument is given
** in the sp_procqmode command.
** If no objectname is given, information about all of the relevant
** objects in the current database is displayed.  If an objectname
** is given as the first argument, only information about it will be
** displayed.
**
** Returned rows consist of the columns:
**
** In default mode:
**   Object Owner.Name, Object type, and Processing mode.
**
** In detail mode:
**   Object Owner.Name, Object type, Processing mode, Subq and Text
**
** where Subq will be 'yes' if subqueries are present or 'no' if
** they are not, and Text will be 'yes' if there is at least one
** row in syscomments for this object, otherwise it will be 'no'.
*/
create procedure sp_procqmode (
@objname varchar(92) = NULL,		/* either NULL or the object
					** name we're after
					*/
@output_mode varchar(10) = 'terse')

as

declare @msg		varchar(250)
declare @object		varchar(50)
declare @owner		varchar(50)
declare @obj_id		int
declare @sptlang	int


if @@trancount = 0
begin
	set transaction isolation level 1
	set chained off
end

select @sptlang = @@langid

if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17100 and 17109
		and langid = @@langid)
	    select @sptlang = 0
end

set nocount on

/* Create a temporary table to hold the rows for the objects of
** interest during processing.  The maximum length of a name is
** 30 characters, but we will be adding the procedure number to
** the names of stored procedures, so the name column has a
** width of 40
*/

create table #TmpQmode(
	name		char(40) null,
	procnum		integer,
	id		integer,
	owner		char(15) null,
	object_type	char(17) null,
	processing_mode	char(19) null,
	subqueries	char(4)  null,
	syscomments	char(4)  null)


if @objname is NULL
begin
	/*
	**  If no @objname given, give a little info about all relevant
	**  objects in this database.  Relevant objects are indetified
	**  by the following conditions:
	**	1. A row must exist in sysprocedures.
	**	2. The object must be either a view, trigger or stored
	**	   procedure, which is determined by the systat field
	**	   of the sysobjects-row for this object:
	**		sysstat & 15  = 2	view
	**		sysstat & 15  = 4	stored procedure
	**		sysstat & 15  = 8	trigger.
	**
	**  Note: 0x80f is the mask for sysstats (=2063decimal).
	** 	  800 is used by Stratus for external tables.
	*/

	/* Insert a row into #TmpQmode for each unique combination of
	** id and procnum in sysprocedures.  NOTE:  There may be 
	** more than one stored procedure with the same id, but with
	** different procnum-values.  Each of these is a seperate
	** procedure and has it's own query tree.
	*/
	insert into #TmpQmode (procnum, id)
		select distinct p.number,
				p.id
		from	sysprocedures p, sysobjects o
		where	p.id = o.id
		and	(o.sysstat & 15) in (2, 4, 8)
		/* Call object_id() so that the access permissions
		** of the current user will be validated.
		*/
		and	o.id = object_id(user_name(o.uid) + '.' + o.name)
end
else
begin

	/*
	**  Make sure the @objname is local to the current database.
	*/
	if @objname like "%.%.%"
	begin
		if substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
		begin
			/* 17460, "Object must be in the current database." */
			exec sp_getmessage 17460, @msg out
			print @msg
			return  (1)
		end
	end

	if not exists (select *
		       from sysobjects
		       where id = object_id(@objname))
	begin
		/*
		**  @objname is not in sysobjects for this user
		*/
		/* 17461, "Object does not exist in this database." */
		exec sp_getmessage 17461, @msg out
		print @msg
		return  (1)
	end

	select @obj_id = object_id(@objname)

	/* Make sure it's the right type of object */
	if not exists (select *
		       from sysobjects
		       where id = @obj_id
		       and sysstat & 15 in (2, 4, 8))
	begin
		/* 18097, "Object must be a trigger,
		** view or stored procedure."
		*/
		exec sp_getmessage 18097, @msg out
		print @msg
		return  (1)
	end

	/* Since an objectname was given, add its id to the qualification
	** in filling up #TmpQmode with objects to display.  We may
	** still get more than one object, if this objectname
	** belongs to a group of stored procedures.
	*/
	insert into #TmpQmode (procnum, id)
		select distinct p.number,
				p.id
		from	sysprocedures p, sysobjects o
		where	p.id = o.id
		and	(o.sysstat & 15) in (2, 4, 8)
		and	o.id = @obj_id

end

/*
** Views and triggers will always have procnum = 0, stored procedures
** can have many values of procnum, with the default being 1. So,
** for objects which have a procnum-value of 0 or 1, the object can
** be uniquely identified by its name ...
*/
update #TmpQmode
	set	name = o.name,
		owner = user_name(uid),
		object_type = convert(char(16), m.description + x.name)
	from	#TmpQmode, sysobjects o,
		master.dbo.spt_values v,
		master.dbo.spt_values x,
		master.dbo.sysmessages m
	where	o.id = #TmpQmode.id
	and	o.sysstat & 2063 = v.number
	and	o.userstat & -32768 = x.number
	and	v.type = "O"
	and	v.msgnum = m.error
	and	isnull(m.langid, 0) = @sptlang
	and	m.error between 17100 and 17109
	and	x.type = "R"
	and	procnum <= 1

/*
** For a stored procedure group, the object name is not unique,
** so add ';x' to the name, where 'x' is the procnum value of
** the object.
*/
update #TmpQmode
	set	name = o.name + ';' + convert(char(9), procnum),
		owner = user_name(uid),
		object_type = convert(char(16), m.description + x.name)
	from	#TmpQmode, sysobjects o,
		master.dbo.spt_values v,
		master.dbo.spt_values x,
		master.dbo.sysmessages m
	where	o.id = #TmpQmode.id
	and	o.sysstat & 2063 = v.number
	and	o.userstat & -32768 = x.number
	and	v.type = "O"
	and	v.msgnum = m.error
	and	isnull(m.langid, 0) = @sptlang
	and	m.error between 17100 and 17109
	and	x.type = "R"
	and	procnum > 1

/*
** If sysstat & 128 > 0, this object has 'System 11 or later'
** processing, otherwise it has pre-System 11 processing.
*/
update	#TmpQmode
set	processing_mode = m.description
from	#TmpQmode t, sysobjects o, master.dbo.sysmessages m
where 	t.id = o.id
and	m.error = 18119
and	isnull(m.langid, 0) = @sptlang
and	o.sysstat2 & 128 = 0

update	#TmpQmode
set	processing_mode = m.description
from	#TmpQmode t, sysobjects o, master.dbo.sysmessages m
where 	t.id = o.id
and	m.error = 18120
and	isnull(m.langid, 0) = @sptlang
and	o.sysstat2 & 128 > 0

/* Check for at least one row in syscomments for this object.
** Note:  texttype = 0, is texttype = SYSCOMMENT.
** First set #TmpQnode.syscomments to 'yes' where syscomments rows exist.
*/
update	#TmpQmode
set	syscomments = m.description
from	#TmpQmode, master.dbo.sysmessages m
where	isnull(m.langid, 0) = @sptlang
and     m.error = 17011
and	exists (select	*
	      from	syscomments c
	      where	c.number = #TmpQmode.procnum
	      and	c.id = #TmpQmode.id
	      and	c.texttype = 0)

/*
** Set #TmpQnode.syscomments to 'no' where syscomments rows don't exist.
*/
update	#TmpQmode
set	syscomments = m.description
from	#TmpQmode, master.dbo.sysmessages m
where	isnull(m.langid, 0) = @sptlang
and     m.error = 17010
and	not exists (select	*
		    from	syscomments c
		    where	c.number = #TmpQmode.procnum
		    and	c.id = #TmpQmode.id
		    and	c.texttype = 0)

/*
** Check whether subqueries are present in the query tree.
** First set #TmpQmode.subqueries to 'yes' where subqueries exist.
*/
update	#TmpQmode
set	subqueries = m.description
from	#TmpQmode, master.dbo.sysmessages m
where	isnull(m.langid, 0) = @sptlang
and     m.error = 17011
and	1 = has_subquery(id, procnum)

/*
** Set #TmpQmode.subqueries to 'no' where subqueries don't exist.
*/
update	#TmpQmode
set	subqueries = m.description
from	#TmpQmode, master.dbo.sysmessages m
where	isnull(m.langid, 0) = @sptlang
and     m.error = 17010
and	0 = has_subquery(id, procnum)

/*
** Delete rows with neither 'yes' nor 'no' values for #TmpQmode.subqueries.
*/
delete
from	#TmpQmode
where	subqueries is null

if (@output_mode = 'detail')
begin
	/* We have 'detail' mode, so print all columns. The width of the
	** owner.objectname field is restricted to 31 chars in this case,
	** to avoid wrap-around on a 80-character display.
	*/
	select	"Object Owner.Name" = convert(char(31), rtrim(owner) + '.'
					+ rtrim(name)),
		"Object Type" = object_type,
		"Processing Mode" = processing_mode,
		"Subq" = subqueries,
		"Text" = syscomments
	from	#TmpQmode
	order by 2 desc, 1 asc
end
else
begin
	/* We have terse mode, so don't print subqueries and syscomments
	** columns.  Because we have fewer columns per output row, the
	** width of the owner.objectname output can be increased to 41
	** and there will still be no wrap-around.
	*/
	select	"Object Owner.Name" = convert(char(41), rtrim(owner) + '.'
					+ rtrim(name)),
		"Object Type" = object_type,
		"Processing Mode" = processing_mode
	from	#TmpQmode
	order by 2 desc, 1 asc
end

return (0)

go
exec sp_procxmode 'sp_procqmode', 'anymode'
go
grant execute on sp_procqmode to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/defaultlanguage */

/*
**  This file defines the primary, foreign, and common keys for the
**  system tables.
*/

/*
**  First do model, then do master.
*/
use model
go

/*
**  Do the primary keys for the system tables.
*/
if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysalternates"))
		execute sp_dropkey primary, sysalternates
go
sp_primarykey sysalternates, suid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syscolumns"))
		execute sp_dropkey primary, syscolumns
go
sp_primarykey syscolumns, id, number, colid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syscomments"))
		execute sp_dropkey primary, syscomments
go
sp_primarykey syscomments, id, number, colid2, colid, texttype
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysdepends"))
		execute sp_dropkey primary, sysdepends
go
sp_primarykey sysdepends, id, number, depid, depnumber
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysindexes"))
		execute sp_dropkey primary, sysindexes
go
sp_primarykey sysindexes, id, indid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syskeys"))
		execute sp_dropkey primary, syskeys
go
sp_primarykey syskeys, id
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysobjects"))
		execute sp_dropkey primary, sysobjects
go
sp_primarykey sysobjects, id
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysprocedures"))
		execute sp_dropkey primary, sysprocedures
go
sp_primarykey sysprocedures, id, number, type, sequence
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysprotects"))
		execute sp_dropkey primary, sysprotects
go
sp_primarykey sysprotects, id, uid, action
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("systypes"))
		execute sp_dropkey primary, systypes
go
sp_primarykey systypes, name
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysusers"))
		execute sp_dropkey primary, sysusers
go
sp_primarykey sysusers, suid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syssegments"))
		execute sp_dropkey primary, syssegments
go
sp_primarykey syssegments, segment
go

/*
**  Now do the foreign keys and common keys.
*/
if exists (select *
		from syskeys
	where type = 2 and id = object_id("sysalternates"))
		execute sp_dropkey foreign, sysalternates, sysusers
go
sp_foreignkey sysalternates, sysusers, suid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syscolumns"))
		execute sp_dropkey common, syscolumns, syscomments
go
sp_commonkey syscolumns, syscomments, id, id
go

sp_dropkey common, syscolumns, syskeys
go
sp_commonkey syscolumns, syskeys, id, key1
go
sp_commonkey syscolumns, syskeys, id, depkey1
go

sp_dropkey common, syscolumns, sysobjects
go
sp_commonkey syscolumns, sysobjects, id, id
go

sp_dropkey common, syscolumns, systypes
go
sp_commonkey syscolumns, systypes, type, type
go
sp_commonkey syscolumns, systypes, usertype, usertype
go
sp_commonkey syscolumns, systypes, domain, domain
go
sp_commonkey syscolumns, systypes, cdefault, tdefault
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syscomments"))
		execute sp_dropkey common, syscomments, sysobjects
go
sp_commonkey syscomments, sysobjects, id, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysdepends"))
		execute sp_dropkey common, sysdepends, sysobjects
go
sp_commonkey sysdepends, sysobjects, id, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysindexes"))
		execute sp_dropkey common, sysindexes, sysobjects
go
sp_commonkey sysindexes, sysobjects, id, id
go

sp_dropkey common, sysindexes, syssegments
go
sp_commonkey sysindexes, syssegments, segment, segment
go

if exists (select *
		from syskeys
	where type = 2 and id = object_id("syskeys"))
		execute sp_dropkey foreign, syskeys, sysobjects
go
sp_foreignkey syskeys, sysobjects, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syskeys"))
		execute sp_dropkey common, syskeys, sysobjects
go
sp_commonkey syskeys, sysobjects, depid, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysobjects"))
		execute sp_dropkey common, sysobjects, sysprocedures
go
sp_commonkey sysobjects, sysprocedures, id, id
go

sp_dropkey common, sysobjects, sysprotects
go
sp_commonkey sysobjects, sysprotects, id, id
go

sp_dropkey common, sysobjects, sysusers
go
sp_commonkey sysobjects, sysusers, uid, uid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysprotects"))
		execute sp_dropkey common, sysprotects, sysusers
go
sp_commonkey sysprotects, sysusers, uid, uid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("systypes"))
		execute sp_dropkey common, systypes, sysusers
go
sp_commonkey systypes, sysusers, uid, uid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysindexes"))
		execute sp_dropkey common, sysindexes, syssegments
go
sp_commonkey sysindexes, syssegments, segment, segment
go

/*
**  Now do the standard systems tables in master.
*/
use master
go

/*
**  Do the primary keys for the system tables.
*/
if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysalternates"))
		execute sp_dropkey primary, sysalternates
go
sp_primarykey sysalternates, suid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syscolumns"))
		execute sp_dropkey primary, syscolumns
go
sp_primarykey syscolumns, id, number, colid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syscomments"))
		execute sp_dropkey primary, syscomments
go
sp_primarykey syscomments, id, number, colid2, colid, texttype
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysdepends"))
		execute sp_dropkey primary, sysdepends
go
sp_primarykey sysdepends, id, number, depid, depnumber
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysindexes"))
		execute sp_dropkey primary, sysindexes
go
sp_primarykey sysindexes, id, indid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syskeys"))
		execute sp_dropkey primary, syskeys
go
sp_primarykey syskeys, id
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysobjects"))
		execute sp_dropkey primary, sysobjects
go
sp_primarykey sysobjects, id
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysprocedures"))
		execute sp_dropkey primary, sysprocedures
go
sp_primarykey sysprocedures, id, number, type, sequence
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysprotects"))
		execute sp_dropkey primary, sysprotects
go
sp_primarykey sysprotects, id, uid, action
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("systypes"))
		execute sp_dropkey primary, systypes
go
sp_primarykey systypes, name
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysusers"))
		execute sp_dropkey primary, sysusers
go
sp_primarykey sysusers, suid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysusages"))
		execute sp_dropkey primary, sysusages
go
sp_primarykey sysusages, dbid, lstart
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysservers"))
		execute sp_dropkey primary, sysservers
go
sp_primarykey sysservers, srvid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysremotelogins"))
		execute sp_dropkey primary, sysremotelogins
go
sp_primarykey sysremotelogins, remoteserverid, remoteusername
go

/*
**  Now do the foreign keys and common keys.
*/
if exists (select *
		from syskeys
	where type = 2 and id = object_id("sysalternates"))
		execute sp_dropkey foreign, sysalternates, sysusers
go
sp_foreignkey sysalternates, sysusers, suid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syscolumns"))
		execute sp_dropkey common, syscolumns, syscomments
go
sp_commonkey syscolumns, syscomments, id, id
go

sp_dropkey common, syscolumns, syskeys
go
sp_commonkey syscolumns, syskeys, id, key1
go
sp_commonkey syscolumns, syskeys, id, depkey1
go

sp_dropkey common, syscolumns, sysobjects
go
sp_commonkey syscolumns, sysobjects, id, id
go

sp_dropkey common, syscolumns, systypes
go
sp_commonkey syscolumns, systypes, type, type
go
sp_commonkey syscolumns, systypes, usertype, usertype
go
sp_commonkey syscolumns, systypes, domain, domain
go
sp_commonkey syscolumns, systypes, cdefault, tdefault
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syscomments"))
		execute sp_dropkey common, syscomments, sysobjects
go
sp_commonkey syscomments, sysobjects, id, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysdepends"))
		execute sp_dropkey common, sysdepends, sysobjects
go
sp_commonkey sysdepends, sysobjects, id, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysindexes"))
		execute sp_dropkey common, sysindexes, sysobjects
go
sp_commonkey sysindexes, sysobjects, id, id
go

sp_dropkey common, sysindexes, syssegments
go
sp_commonkey sysindexes, syssegments, segment, segment
go

if exists (select *
		from syskeys
	where type = 2 and id = object_id("syskeys"))
		execute sp_dropkey foreign, syskeys, sysobjects
go
sp_foreignkey syskeys, sysobjects, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syskeys"))
		execute sp_dropkey common, syskeys, sysobjects
go
sp_commonkey syskeys, sysobjects, depid, id
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysobjects"))
		execute sp_dropkey common, sysobjects, sysprocedures
go
sp_commonkey sysobjects, sysprocedures, id, id
go

sp_dropkey common, sysobjects, sysprotects
go
sp_commonkey sysobjects, sysprotects, id, id
go

sp_dropkey common, sysobjects, sysusers
go
sp_commonkey sysobjects, sysusers, uid, uid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysprotects"))
		execute sp_dropkey common, sysprotects, sysusers
go
sp_commonkey sysprotects, sysusers, uid, uid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("systypes"))
		execute sp_dropkey common, systypes, sysusers
go
sp_commonkey systypes, sysusers, uid, uid
go

/*
**  These are in the master database only.
*/
/*  Define primary keys first */
if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysconfigures"))
		execute sp_dropkey primary, sysconfigures
go
sp_primarykey sysconfigures, config
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysdatabases"))
		execute sp_dropkey primary, sysdatabases
go
sp_primarykey sysdatabases, name
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysdevices"))
		execute sp_dropkey primary, sysdevices
go
sp_primarykey sysdevices, name
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("syslogins"))
		execute sp_dropkey primary, syslogins
go
sp_primarykey syslogins, suid
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysmessages"))
		execute sp_dropkey primary, sysmessages
go
sp_primarykey sysmessages, error, dlevel
go

if exists (select *
		from syskeys
	where type = 1 and id = object_id("sysusages"))
		execute sp_dropkey primary, sysusages
go
sp_primarykey sysusages, dbid, lstart
go

/*
**  Now the foreign and common keys.
*/
if exists (select *
		from syskeys
	where type = 3 and id = object_id("syscurconfigs"))
		execute sp_dropkey common, syscurconfigs, sysconfigures
go
sp_commonkey syscurconfigs, sysconfigures, config, config
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysdatabases"))
		execute sp_dropkey common, sysdatabases, syslocks
go
sp_commonkey sysdatabases, syslocks, dbid, dbid
go

sp_dropkey common, sysdatabases, syslogins
go
sp_commonkey sysdatabases, syslogins, suid, suid
go

sp_dropkey common, sysdatabases, sysprocesses
go
sp_commonkey sysdatabases, sysprocesses, dbid, dbid
go

sp_dropkey common, sysdatabases, sysusages
go
sp_commonkey sysdatabases, sysusages, dbid, dbid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syslocks"))
		execute sp_dropkey common, syslocks, sysprocesses
go
sp_commonkey syslocks, sysprocesses, spid, spid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("syslogins"))
		execute sp_dropkey common, syslogins, sysprocesses
go
sp_commonkey syslogins, sysprocesses, suid, suid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysservers"))
		execute sp_dropkey common, sysservers, sysremotelogins
go
sp_commonkey sysservers, sysremotelogins, srvid, remoteserverid
go

if exists (select *
		from syskeys
	where type = 3 and id = object_id("sysremotelogins"))
		execute sp_dropkey common, sysremotelogins, sysusers
go
sp_commonkey sysremotelogins, sysusers, suid, suid
go

dump transaction master to diskdump with truncate_only
go

dump transaction model to diskdump with truncate_only
go

use sybsystemprocs
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_reportstats')
begin
	drop procedure sp_reportstats
end
go
print "Installing sp_reportstats"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/reportstats */

/*
**  This stored procedure prints out Chargeback Accounting Statistics and
**  percentages.
*/

/*
** Messages for "sp_reportstats"        17935
**
** 17231, "No login with the specified name exists."
**
** NOTE: We need to LOCALIZE the column names of the SELECTs below!!
**
*/

create procedure sp_reportstats
@loginame varchar(30) = NULL		/* name of login to report */
as

declare @msg varchar(255)
declare @cnt int,
	@cputot int,
	@iotot int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

begin transaction

/*
**  Get totals for all logins except sa.
**  If the total is zero all users have
**  used zero time so far. Change totals
**  to random value (1) and go on. 
**  % usage calculations will appropriately
**  result in zero this way.
*/
select	@cputot = convert(float, sum(totcpu)), 
	@iotot = convert(float, sum(totio))
	from master.dbo.syslogins holdlock

if @cputot = 0
	select @cputot = 1

if @iotot = 0
	select @iotot = 1

if @loginame is not NULL
begin

	if not exists (select * 
			from master.dbo.syslogins 
			where name like @loginame)
	begin
		/* 17231, "No login with the specified name exists." */
		exec sp_getmessage 17231, @msg output
		print @msg
		rollback transaction
		return (1)
	end

	/*
	**  Print out the totals for this login, and compare against 
	**  overall totals.
	*/
	select "Name" = name, "Since" = convert(char(11), accdate),
		"CPU" = totcpu, 
		"Percent CPU" = convert(varchar(9), convert(numeric(14,4),
				        round(convert(numeric(20,4), 
					totcpu) / @cputot * 100, 5) ) )
			+ "%",
		"I/O" = totio,
		"Percent I/O" = convert(varchar(9), convert(numeric(14,4),
				        round(convert(numeric(20,4), 
					totio) / @iotot * 100, 5) ) )
			+ "%"
		from master.dbo.syslogins where name like @loginame

end
else
begin

	/*
	**  Print out the totals for all logins except sa, and compare against 
	**  overall totals.
	*/
	select "Name" = name, "Since" = convert(char(11), accdate),
		"CPU" = totcpu, 
		"Percent CPU" = convert(varchar(9), convert(numeric(14,4),
				        round(convert(numeric(20,4), 
					totcpu) / @cputot * 100, 5) ) ) 
			+ "%",
		"I/O" = totio,
		"Percent I/O" = convert(varchar(9), convert(numeric(14,4),
				        round(convert(numeric(20,4), 
					totio) / @iotot * 100, 5) ) )
			+ "%"
		from master.dbo.syslogins
end

/*
**  Print out overall totals.
*/
print ""
select "Total CPU" = @cputot, "Total I/O" = @iotot
commit transaction
return (0)

go
exec sp_procxmode 'sp_reportstats', 'anymode'
go
grant execute on sp_reportstats to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_clearstats')
begin
	drop procedure sp_clearstats
end
go
print "Installing sp_clearstats"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/clearstats */

/*
** Messages for "sp_clearstats"         17900
**
** 17231, "No login with the specified name exists."
** 17260, "Can't run %1! from within a transaction."
** 17900, "%1! login account(s) cleared."
*/

/*
**  This stored procedure prints out Chargeback Accounting Statistics and
**  percentages using sp_reportstats. In addition, it resets the accounting
**  date, cpu usage, and I/O usage information.
*/
create procedure sp_clearstats
@loginame varchar(30) = NULL		/* name of login to clear */
as

declare @msg varchar(255)
declare @cnt int,
	@cputot int,
	@iotot int
declare @msg_cnt  varchar(10)


/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_clearstats"
        return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sa_role") = 0)
	return (1)

begin transaction

if @loginame is not NULL
begin

	if not exists (select * from master.dbo.syslogins where name like @loginame)
	begin
		/*
		** 17231, "No login with the specified name exists."
		*/
		exec sp_getmessage 17231, @msg output
		print @msg
		rollback transaction
		return (1)
	end

	/*
	**  Print out the statistics.
	*/
	execute sp_reportstats @loginame

	/*
	**  Update the login, setting the totcpu and totio columns to 0, and
	**  the accdate to current time.
	*/
	update master.dbo.syslogins 
		set accdate = getdate(), totcpu = 0, totio = 0
			where name like @loginame

end
else
begin

	/*
	**  Print out the statistics.
	*/
	execute sp_reportstats

	/*
	**  Update the login, setting the totcpu and totio columns to 0, and the
	**  accdate to current time.
	*/
	update master.dbo.syslogins 
		set accdate = getdate(), totcpu = 0, totio = 0

end
/*
**  Check @@rowcount when it works
*/
select @cnt = @@rowcount
if @cnt > 0
begin
	/*
	** 17900, "%1! login account(s) cleared."
	*/
	exec sp_getmessage 17900, @msg output
	select @msg_cnt = rtrim(convert(char(10), @cnt))
	print @msg, @msg_cnt
end
commit transaction
return (0)

go
exec sp_procxmode 'sp_clearstats', 'anymode'
go
grant execute on sp_clearstats to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_datatype_info')
begin
	drop procedure sp_datatype_info
end
go
print "Installing sp_datatype_info"
go


/* 
** Sccsid = "%Z% generic/sproc/%M% %I% %G%"
**
** History:
**	10.0	steven	1.1	07/13/93	sproc/src/datatype_info
**						Ported from MS catalog SP's
**
** Implementation Notes:
** 	The messiness of 'sp_data_type_info' was to get around the
** problem of returning the correct lengths for user defined types.  The
** join on the type name ensures all user defined types are returned, but
** this puts a null in the data_type column.  By forcing an embedded
** select and correlating it with the current row in systypes, we get the
** correct data_type mapping even for user defined types.  
*/

create procedure sp_datatype_info
@data_type int = 0			/* Provide datatype_info for type # */
as
	if (select @data_type) = 0
		select	/* Real SQL Server data types */
			type_name = t.name,
			d.data_type,
			"precison" = isnull(d.data_precision, 
					    convert(int,t.length)),
			d.literal_prefix,
			d.literal_suffix,
			e.create_params,
			d.nullable,
			d.case_sensitive,
			d.searchable,
			d.unsigned_attribute,
			d.money,
			d.auto_increment,
			d.local_type_name
		from 	sybsystemprocs.dbo.spt_datatype_info d, 
			sybsystemprocs.dbo.spt_datatype_info_ext e, systypes t
		where
			d.ss_dtype = t.type
			and t.usertype *= e.user_type
			    /* restrict results to "real" datatypes */
			and t.name not in ("nchar","nvarchar",
					   "sysname","timestamp",
					   "datetimn","floatn","intn","moneyn")
			and t.usertype < 100	/* No user defined types */
		UNION
		select	/* SQL Server user data types */
			type_name = t.name,
			d.data_type,
			"precison" = isnull(d.data_precision, 
					    convert(int,t.length)),
			d.literal_prefix,
			d.literal_suffix,
			e.create_params,
			d.nullable,
			d.case_sensitive,
			d.searchable,
			d.unsigned_attribute,
			d.money,
			d.auto_increment,
			t.name
		from 	sybsystemprocs.dbo.spt_datatype_info d, 
			sybsystemprocs.dbo.spt_datatype_info_ext e, systypes t
		where
			d.ss_dtype = t.type
			and t.usertype *= e.user_type
			    /* 
			    ** Restrict to user defined types (value > 100)
			    ** and Sybase user defined types (listed)
			    */
			and (t.name in ("nchar","nvarchar",
					    "sysname","timestamp")
			    or t.usertype >= 100)      /* User defined types */
		order by d.data_type, type_name
	else
		select	/* Real SQL Server data types */
			type_name = t.name,
			d.data_type,
			"precison" = isnull(d.data_precision, 
					    convert(int,t.length)),
			d.literal_prefix,
			d.literal_suffix,
			e.create_params,
			d.nullable,
			d.case_sensitive,
			d.searchable,
			d.unsigned_attribute,
			d.money,
			d.auto_increment,
			d.local_type_name
		from 	sybsystemprocs.dbo.spt_datatype_info d, 
			sybsystemprocs.dbo.spt_datatype_info_ext e, systypes t
		where
			data_type = @data_type
			and d.ss_dtype = t.type
			and t.usertype *= e.user_type
			    /* restrict results to "real" datatypes */
			and t.name not in ("nchar","nvarchar",
					   "sysname","timestamp",
					   "datetimn","floatn","intn","moneyn")
			and t.usertype < 100	/* No user defined types */
		UNION
		select	/* SQL Server and user data types */
			type_name = t.name,
			d.data_type,
			"precison" = isnull(d.data_precision, 
					    convert(int,t.length)),
			d.literal_prefix,
			d.literal_suffix,
			e.create_params,
			d.nullable,
			d.case_sensitive,
			d.searchable,
			d.unsigned_attribute,
			d.money,
			d.auto_increment,
			t.name
		from 	sybsystemprocs.dbo.spt_datatype_info d, 
			sybsystemprocs.dbo.spt_datatype_info_ext e, systypes t
		where
			data_type = @data_type
			and d.ss_dtype = t.type
			and t.usertype *= e.user_type
			    /* 
			    ** Restrict to user defined types (value > 100)
			    ** and Sybase user defined types (listed)
			    */
			and (t.name in ("nchar","nvarchar",
					    "sysname","timestamp")
			    or t.usertype >= 100)     /* User defined types */
		order by type_name
return (0)
go
exec sp_procxmode 'sp_datatype_info', 'anymode'
go
grant execute on sp_datatype_info to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_addmessage')
begin
	drop procedure sp_addmessage
end
go
print "Installing sp_addmessage"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/* generic/sproc/addmessage	14.2	4/25/91 */

/* 
** Messages from sysmessages
**
** 17210, "Message number must be at least 20000."
** 17211, "Cannot add message until Sysusermessages system table is created properly by Upgrade."
** 17201, "'%1!' is not an official language name from Syslanguages."
** 17212, "A message with number %1! in the specified language already exists."
** 17213, "Drop the old message first if you still wish to add this one."
** 17214, "The message has been inserted."
*/
create procedure sp_addmessage
@message_num int,
@message_text varchar(255),
@language varchar(30) = NULL
as

    declare @msg varchar(255)
    declare @returncode int




    /* Use the default language by default */
    declare @lang_id smallint 
    select @lang_id = @@langid


    if @@trancount = 0
    begin
    	set chained off
    end
    set transaction isolation level 1

    if @message_num < 20000
    BEGIN
	/* 17210, "Message number must be at least 20000." */
        exec sp_getmessage 17210, @msg output
        print @msg
        return (1)
    END

    /*
    ** Check to be sure Sysusermessages exists
    */
    if not exists (select * from sysobjects
    			where name = "sysusermessages"
    			and type = 'S')
    BEGIN
        /* 
	** 17211, "Cannot add message until Sysusermessages system table is
	**		created properly by Upgrade."
        */
        exec sp_getmessage 17211, @msg output
        print @msg
        return (1)
    END

    /*
    ** Check that language is valid.
    */
    if @language is not NULL
    BEGIN
        execute @returncode = sp_validlang @language
        if @returncode != 0
        begin
                /* Us_english is always valid */
                if @language != "us_english"
		BEGIN
		    	/* 
			** 17201, "'%1!' is not an official language
			**	name from Syslanguages."
			*/
		    	exec sp_getmessage 17201, @msg output
		    	print @msg, @language
		    	return @returncode
		END

		/* set to us_english */
		select @lang_id = NULL
        end

	else
	select @lang_id = langid from master.dbo.syslanguages
		    where @language = name
    END

    /* The langid is assigned 0 since it gets its value from @@langid. */
    /* For us_english, we have to insert it as NULL and not 0, this is */
    /* to maintain compatibility with the current conventions          */

    if @lang_id = 0
    begin
        select @lang_id = NULL
    end

    /*
    ** Make sure the message doesn't already exist.
    */
    if exists (select *
    		from sysusermessages 
    	where error = @message_num and langid = @lang_id)
    BEGIN
	/* 17212, "A message with number %1! in the specified language already exists." */
        exec sp_getmessage 17212, @msg output
        print @msg, @message_num

	/* 17213, "Drop the old message first if you still wish to add this one." */
        exec sp_getmessage 17213, @msg output
        print @msg
        return (1)
    END

    /*
    ** Check that the message is a valid one.
    */
    print @message_text, "<arg1>", "<arg2>", "<arg3>", "<arg4>",
    		    "<arg5>", "<arg6>", "<arg7>", "<arg8>",
    		    "<arg9>", "<arg10>", "<arg11>", "<arg12>",
    		    "<arg13>", "<arg14>", "<arg15>", "<arg16>",
    		    "<arg17>", "<arg18>", "<arg19>", "<arg20>"

    /*
    ** If there was an error, @@error will be non-zero
    */
    if @@error != 0
           return (1)

    /* Now, insert the message */
    insert into sysusermessages
    	    values(@message_num, suser_id(), @message_text, @lang_id)
    if @@error != 0
	return(1)
    else
    begin
    	/* 17214, "The message has been inserted." */
	exec sp_getmessage 17214, @msg output
        print @msg
    end
    return (0)
go
exec sp_procxmode 'sp_addmessage', 'anymode'
go
grant execute on sp_addmessage to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropmessage')
begin
	drop procedure sp_dropmessage
end
go
print "Installing sp_dropmessage"
go

/* Sccsid = "@(#) generic/sproc/src/%M% %I% %G%" */
/* generic/sproc/dropmessage		14.2	11/12/91 */

/* 
** Messages from sysmessages
**
** 17201, "'%1!' is not an official language name from Syslanguages."
** 17202, "Message number %1! does not exist in the %2! language."
** 17210, "Message number must be at least 20000."
** 17220, "Message number %1! does not exist."
** 17221, "Message deleted."
** 17222, "User '%1!' does not have permission to drop message number %2!."
** 17223, "User '%1!' does not have permission to drop message number %2! in the %3! language."
*/     

create procedure sp_dropmessage
@message_num int, 
@language varchar(30) = NULL
as

declare @msg varchar(255)
declare @msg2 varchar(30)
declare @lang_id smallint
declare @privileged smallint
declare @returncode smallint
declare @procval int


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/*
** Checking "OWN"ership of the message by the user is on by default by
** resetting the "priveleged" flag. This is bypassed if needed by setting it
** to 1
*/
select @privileged = 0

/*
**  Only the Database Owner (DBO) or
**  Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
**  Check sa_role first as it cleans up the code.
*/
if charindex("sa_role", show_role()) > 0
begin
	/*
	** If user has sa_role, wether by explicit granting or by being
	** SA or DBO we assume that "sa_role" is being used to drop the
	** message & thus we want to send an audit record by calling
	** proc_role("sa_role") & we set the privileged flag to say that
	** this does not have to be the owner of the message being dropped
	*/
	select @procval = proc_role("sa_role")
	select @privileged = 1
end
else
begin
	/*
	** If this is the DBO then set privileged flag to check that 
	** ownership of the message is not to be checked
	*/
	if user_id() = 1
	begin
		select @privileged = 1
	end
end

/*
** Check that language is valid.
*/
if @language is null
	select @lang_id = -1		/* (all) */
else
BEGIN
	execute @returncode = sp_validlang @language
	if @returncode != 0
	begin
		/* Us_english is always valid */
                if @language != "us_english"
		BEGIN
			/* 
			** 17201, "'%1!' is not an official language
			**		name from Syslanguages."
			*/
			exec sp_getmessage 17201, @msg output
			print @msg, @language
			return @returncode
		END

		/* set to us_english */
		select @lang_id = NULL
        end

	else
	select @lang_id = langid from master.dbo.syslanguages
			where @language = name
END

if @message_num < 20000
begin
	/* 17210, "Message number must be at least 20000." */
        exec sp_getmessage 17210, @msg output
        print @msg
        return (1)
end

/*
** Check that message exists 
*/
if not exists (select * from sysusermessages
			    where error = @message_num)
begin
	/* 17220, "Message number %1! does not exist." */
	exec sp_getmessage 17220, @msg output
	print @msg, @message_num
	return (1)
end



/*
** ... In the Proper language
*/
if @lang_id != -1 and not exists (select * from sysusermessages
		    where error = @message_num and langid = @lang_id)
begin
	/* 17202, "Message number %1! does not exist in the %2! language." */
	exec sp_getmessage 17202, @msg output
	print @msg, @message_num, @language
	return (1)
end

if (@privileged = 1)
BEGIN
	/*
	** Do they want to delete all the messages?
	*/
	if @lang_id = -1
	begin
		delete sysusermessages
				where error = @message_num
		/* 17221, "Message deleted." */
		exec sp_getmessage 17221, @msg output
		print @msg
	end		
	/*
	** If not, delete only the message with the
	** specific language
	*/
	else
	begin
		delete sysusermessages 
			where error = @message_num and
					langid = @lang_id
		/* 17221, "Message deleted." */
		exec sp_getmessage 17221, @msg output
		print @msg
	end
     END
    else
    /* Only delete the user's specific messages */
     BEGIN
	/*
	** Do they want to delete all the messages?
	*/
	if @lang_id = -1
	begin
		if exists (select * from sysusermessages
			    where error = @message_num
					and uid = suser_id())
		begin
			delete sysusermessages
			where error = @message_num
					and uid = suser_id()
			/* 17221, "Message deleted." */
			exec sp_getmessage 17221, @msg output
			print @msg
		end
		else
		begin
			/* 
			** 17222 "User '%1!' does not have permission to 
			** 		drop message number %2!"
			*/
			exec sp_getmessage 17222, @msg output
			select @msg2 = user_name()
			print @msg, @msg2, @message_num
		end
	end		
	/*
	** If not, delete only the message with the
	** specific language
	*/
       else
	if exists (select * from sysusermessages
			where error = @message_num
					and langid = @lang_id
					and uid = suser_id())
	begin
		delete sysusermessages 
				where error = @message_num
						and langid = @lang_id
						and uid = suser_id()
		/* 17221, "Message deleted." */
		exec sp_getmessage 17221, @msg output
		print @msg
	end
       else
	begin
		/* 
		** 17223 "User '%1!' does not have permission to 
		** 		drop message number %2! in the %3! language."
		*/
		exec sp_getmessage 17223, @msg output
		select @msg2 = user_name()
		print @msg, @msg2, @message_num, @language
		return (1)
	end
    END		

    return (0)
go
exec sp_procxmode 'sp_dropmessage', 'anymode'
go
grant execute on sp_dropmessage to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindmsg')
begin
	drop procedure sp_bindmsg
end
go
print "Installing sp_bindmsg"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	5.0	1.1	07/31/91	sproc/src/bindmsg */

/*
** Messages for "sp_bindmsg"            17890
**
** 17890, "Constraint name must be in `current' database."
** 17891, "Constraint name must belong to the current user."
** 17892, "Message id must be a user defined message."
** 17893, "No such message exists. Please create the message first using sp_addmessage."
** 17894, "No such referential or check constraint exists. Please check whether
** the constraint name is correct."
** 17895, "Constraint is bound to a message. You must unbind the message first."
** 17896, "Binding message failed unexpectedly. Please try again."
** 17897, "Message bound to constraint."
*/

create procedure sp_bindmsg
@constrname varchar(92),		/* name of the constraint */
@msgid int 				/* message id */
as

declare @msg varchar(255)		/* for printing messages */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

/* check to see that the object name  is local to the current database */

if (@constrname like "%.%.%")
begin
	/*
	** 17890, "Constraint name must be in `current' database."
	*/
	exec sp_getmessage 17890, @msg output
	print @msg
	return (1)
end

/* check to see that the object name belongs to the current user */

if (@constrname like "%.%")
begin
	/*
	** 17891, "Constraint name must belong to the current user."
	*/
	exec sp_getmessage 17891, @msg output
	print @msg
	return (1)
end

/* check if the message number is illegal */

if (@msgid < 20000)
begin
	/*
	** 17892,  "Message id must be a user defined message."
	*/
	exec sp_getmessage 17892, @msg output
	print @msg
	return (1)
end

/* check if the message number is nonexistent */

if not exists (select * from sysusermessages where error = @msgid)
begin
	/*
	** 17893, "No such message exists. Please create the message first using sp_addmessage."
	*/
	exec sp_getmessage 17893, @msg output
	print @msg
	return (1)
end


/* check to see that the constraint exists */

if not exists (select id
		from sysconstraints c, sysobjects o
		where c.constrid = object_id (@constrname)
			and o.id = object_id (@constrname)
			and o.uid = user_id ()
			and (o.sysstat & 15 = 7 /* check constraint */
			or sysstat & 15 = 9) /* referential constraint */ )
begin
	/*
	** 17894, "No such referential or check constraint exists. Please check whether the constraint name is correct."
	*/
	exec sp_getmessage 17894, @msg output
	print @msg
	return (1)
end

/*
**
** NOTE: If the following section of code is ever "uncommented", change
** the @constrid variable in the SQL Statement to object_id(@constrname).
**
** check if the constraint is already bound to a message
**
** if (exists (select *
**		from sysconstraints
**		where constrid = @constrid
**			and error != 0))
** begin
**	**
** 	** 17895, "Constraint is bound to a message. You must unbind the message first."
**	**
**	exec sp_getmessage 17895, @msg output
**	print @msg
**	return (1)
** end
*/

/* update sysconstraints table */

update sysconstraints
	set error = @msgid
	from sysconstraints, sysobjects
	where sysconstraints.constrid = object_id(@constrname)
		and sysobjects.id = object_id(@constrname)
		and sysobjects.uid = user_id ()
		and (sysstat & 15 = 7 /* check constraint */
		or sysstat & 15 = 9) /* referential constraint */

/* check if the update took place */

if @@rowcount != 1
begin
	/*
	** 17896, "Binding message failed unexpectedly. Please try again."
	*/
	exec sp_getmessage 17896, @msg output
	print @msg
	return (1)
end

/*
** Since binding a message is a schema change, update schema count
** for the object in the sysobjects table.
*/

 update sysobjects
 set schemacnt = schemacnt + 1
 from sysobjects, sysconstraints
 where sysconstraints.constrid = object_id(@constrname)
	and sysobjects.id = sysconstraints.tableid
	and uid = user_id()
	and schema_inc (sysobjects.id) is NULL
	and (sysstat & 15 = 7 /* check constraint */
	or sysstat & 15 = 9) /* referential constraint */

/*
** 17897, "Message bound to constraint."
*/
exec sp_getmessage 17897, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_bindmsg', 'anymode'
go
grant execute on sp_bindmsg to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindmsg')
begin
	drop procedure sp_unbindmsg
end
go
print "Installing sp_unbindmsg"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	5.0	1.1	07/31/91	sproc/src/unbindmsg */

/*
** Messages for "sp_unbindmsg"          17940
**
** 17890, "Constraint name must be in `current' database."
** 17891, "Constraint name must belong to the current user."
** 17894, "No such referential or check constraint exists. Please check whether
** the constraint name is correct."
** 17940, "Constraint is not bound to any message."
** 17941, "Unbinding message failed unexpectedly. Please try again."
** 17942, "Message unbound from constraint."
*/

create procedure sp_unbindmsg

@constrname varchar(92)			/* name of the constraint */
as

declare @msg varchar(250)		/* message text */


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

/* check to see that the object names are local to the current database */

if (@constrname like "%.%.%")
begin
	/* 17890, "Constraint name must be in `current' database." */
	exec sp_getmessage 17890, @msg output
	print @msg
	return (1)
end

/* check to see that the object name belongs to the current user */

if (@constrname like "%.%")
begin
	/* 17891, "Constraint name must belong to the current user." */
	exec sp_getmessage 17891, @msg output
	print @msg
	return (1)
end

/* check to see that the constraint exists */

if not exists (select id
		from sysconstraints c, sysobjects o
		where c.constrid = object_id (@constrname)
			and o.id = object_id (@constrname)
			and o.uid = user_id ()
			and (sysstat & 15 = 7 /* check constraint */
			or sysstat & 15 = 9) /* referential constraint */ )
begin
	/*
	** "No such referential or check constraint exists. Please check whether the constraint name is correct."
	*/
	exec sp_getmessage 17894, @msg output
	print @msg
	return (1)
end

/* check if the constraint is bound to a message */

if exists (select c.error
		from sysconstraints c, sysobjects
		where c.constrid = object_id(@constrname)
			and sysobjects.id = object_id(@constrname)
			and sysobjects.uid = user_id ()
			and (sysstat & 15 = 7 /* check constraint */
			or sysstat & 15 = 9) /* referential constraint */ 
			and c.error = 0)
begin
	/*
	** 17940, "Constraint is not bound to any message."
	*/
	exec sp_getmessage 17940, @msg output
	print @msg
	return (1)
end

/* update sysconstraints table */

update sysconstraints
	set error = 0
	from sysconstraints, sysobjects
	where sysconstraints.constrid = object_id(@constrname)
		and sysobjects.id = object_id(@constrname)
		and sysobjects.uid = user_id ()
		and (sysstat & 15 = 7 /* check constraint */
		or sysstat & 15 = 9) /* referential constraint */ 

/* check if the update took place */

if @@rowcount != 1
begin
	/*
	** 17941, "Unbinding message failed unexpectedly. Please try again."
	*/
	exec sp_getmessage 17941, @msg output
	print @msg
	return (1)
end

/*
** Since unbinding a message is a schema change, update schema count
** for the object in the sysobjects table.
*/

 update sysobjects
 set schemacnt = schemacnt + 1
 from sysobjects, sysconstraints
 where sysconstraints.constrid = object_id(@constrname)
	and sysobjects.id = sysconstraints.tableid
	and uid = user_id()
	and schema_inc (sysobjects.id) is NULL
	and (sysstat & 15 = 7 /* check constraint */
	or sysstat & 15 = 9) /* referential constraint */ 

/*
** 17942, "Message unbound from constraint."
*/
exec sp_getmessage 17942, @msg output
print @msg

return (0)
go
exec sp_procxmode 'sp_unbindmsg', 'anymode'
go
grant execute on sp_unbindmsg to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_role')
begin
	drop procedure sp_role
end
go
print "Installing sp_role"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	5.0	1.0	10/22/91	sproc/src/role */

/* 
** Messages for "sp_role"               17880 
**
** 17260, "Can't run %1! from within a transaction."
** 17880, "No such account -- nothing changed."
** 17881, "Invalid role -- nothing changed."
** 17882, "Invalid role -- nothing changed. The user must already 
**		possess 'sa' before being granted the Sybase technical 
**		support role."
** 17883, "Cannot revoke the SSO role from the last remaining unlocked SSO
**	   login."
** 18046, "Cannot revoke the SA role from the last remaining unlocked SA login."
** 17884, "Neither 'grant' or 'revoke' is specified -- nothing changed."
** 17885, "Role updated."
** 17886, "Error in updating role."
** 17915, "Warning:  the specified account is currently active."
** 17918, "Nothing changed."
*/

create procedure sp_role
@action  varchar(30),                   /* "grant" or "revoke"	*/
@rolename varchar(30),			/* role name	*/
@loginame varchar(30)			/* user account name	*/
as
declare @suid int			/* suid of account	*/
declare @role int			/* role	*/	
declare @oldrole int			/* original role */	
declare @msg varchar(250)		/* Message text */
declare @srid int			/* role id	*/

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/* 17260, "Can't run %1! from within a transaction." */
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_role"
	return (1)
end

/*  Check if the account exists */
select @suid = suid
	from master.dbo.syslogins
	where name = @loginame
if @suid is NULL
begin
	/*
        ** 17880, "No such account -- nothing changed."
	*/
	exec sp_getmessage 17880, @msg output
	print @msg
        return (1)
end


/* check if user has sso role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
** If the role being granted/revoked is SA role, the caller must be
** have the SA role also (ECO 41530).
*/

if (@rolename = "sa_role")
begin
	if (proc_role("sa_role") = 0)
		return (1)
end
else
begin
	if (proc_role("sso_role") = 0)
        	return (1)
end

/*
**  Determine which required role to set/reset.
*/
select @srid = srid
	from master.dbo.syssrvroles
	where name = @rolename
if @@rowcount != 1
begin
	/*
	** 17881, "Invalid role -- nothing changed."
	*/
	exec sp_getmessage 17881, @msg output
	print @msg
	return (1)
end

/*
**  Update actually takes place here
*/
if @action = "grant"
begin
	/* 
	** The user must already possess "sa_role" before being granted 
	** the sybase technical support role. 
	*/
	if (@rolename = "sybase_ts_role")
	begin
		if (select count(*) 
			from master.dbo.sysloginroles a,
			     master.dbo.syssrvroles b
			where a.suid = @suid and b.name = "sa_role" and
			      a.srid = b.srid) = 0
		begin
			/*
			** 17882, "Invalid role -- nothing changed. 
			** The user must already possess 'sa' before being 
			** granted the Sybase technical support role.
			*/
			exec sp_getmessage 17882, @msg output
			print @msg
			return (1)
		end
	end

	/* if user does not belong to the role add row */
	if (select count(srid)
		from master.dbo.sysloginroles
		where srid = @srid and suid = @suid) = 0
	begin
		insert master.dbo.sysloginroles values (@suid,@srid,0)
	end
end
else if @action = "revoke"
begin
	/*  Check if the account has already logged in. */
	if exists (select * from master.dbo.sysprocesses where suid = @suid)
	begin
		/* 17915,
		** "Warning: the specified account is currently active."
		*/
		exec sp_getmessage 17915, @msg output
		print @msg
		/*
		** 17918, "Nothing changed."
		*/
		exec sp_getmessage 17918, @msg output
		print @msg
		return (1)
	end

	/*
	**  We can't allow the last unlocked SSO and SA logins to have those,
	**  particular roles revoked, because the system would then become
	**  hosed because no one could ever get that role back.  So check and
	**  prevent both cases.
	*/
	if ((@rolename = "sso_role") and
	    (select count(suid) from master.dbo.syslogins
		where (status & 2) = 0 and suid in
			(select suid from master.dbo.sysloginroles
				where srid = 1)) = 1) and
	    ((select count(suid) from master.dbo.sysloginroles
		where suid = @suid and srid = 1) = 1)
	begin
		/*
		** 17883, "Cannot revoke the SSO role from the last remaining
		**	   unlocked SSO login."
		*/
		exec sp_getmessage 17883, @msg output
		print @msg
		return (1)
	end

	if ((@rolename = "sa_role") and
	    (select count(suid) from master.dbo.syslogins
		where (status & 2) = 0 and suid in
			(select suid from master.dbo.sysloginroles
				where srid = 0)) = 1) and
	    ((select count(suid) from master.dbo.sysloginroles
		where suid = @suid and srid = 0) = 1)
	begin
		/*
		** 18046, "Cannot revoke the SA role from the last remaining
		**	   unlocked SA login."
		*/
		exec sp_getmessage 18046, @msg output
		print @msg
		return (1)
	end

	/* revoke "role" from user */
	if (select count(srid) from master.dbo.sysloginroles
	   where @srid = srid) > 0  	
		delete master.dbo.sysloginroles
		where @srid = srid and @suid = suid
	/* 
	** revoking "sa_role" also revokes the sybase technical support
	** role 
	*/
	if (@rolename = "sa_role")
	begin
		/* revoke "role" from user */
		if (select count(srid) from master.dbo.sysloginroles
	   	   where srid = 3 and suid = @suid) > 0  	
			delete master.dbo.sysloginroles
			where srid = 3 and @suid = suid
	end
end
else
begin
	/*
	** 17884, "Neither 'grant' or 'revoke' is specified -- nothing changed."
	*/
	exec sp_getmessage 17884, @msg output
	print @msg
	return (1)
end

/*
** 17885, "Role updated."
*/
exec sp_getmessage 17885, @msg output
print @msg
return (0)
go
exec sp_procxmode 'sp_role', 'anymode'
go
grant execute on sp_role to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_modifylogin')
begin
	drop procedure sp_modifylogin
end
go
print "Installing sp_modifylogin"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	5.0	1.0	10/22/91	sproc/src/modifylogin */

/*
** Messages for "sp_modifylogin"        17920 
** 
** 17260, "Can't run %1! from within a transaction." 
** 17880, "No such account -- nothing changed." 
** 17920, "The given security label value is syntactically wrong."
** 17921, "The given maxwrite value cannot dominate the minwrite value from 
**		syslogins -- nothing changed."
** 17922, "The given minwrite value is not dominated by the maxwrite value from 
**		syslogins -- nothing changed."
** 17923, "The given security label is not dominated by the clearance value from 
**		syslogins -- nothing changed."
** 17924, "The given clearance value cannot dominate the %1! value from syslogins 
**		-- nothing changed."
** 17925, "Column name invalid -- nothing changed."
** 17926, "Column changed."
** 17927, "Error in changing the value of the specified column."
*/

create procedure sp_modifylogin
@account varchar(30),		/* the name of the account  */
@column  varchar(30),		/* the column to be updated */
@value   varchar(255)		/* the new value of column  */
as
declare @suid int		/* suid of account to be modified   */
declare @msg varchar(250)	/* message text */
declare @retstat int		/* return status from other procedures */

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/* 17260, "Can't run %1! from within a transaction." */
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_modifylogin"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/*
** If user is trying to modify someone else's login then
** check if user has sa role. Proc_role will perform auditing
** and print error message if required.
*/

if (suser_id(@account) != suser_id())
begin
	if (proc_role("sa_role") = 0)
		return (1)
end

/*  Check if the account exists */
select @suid = suid
	from master.dbo.syslogins
	where name = @account
if @suid is NULL
begin
	/*
	** 17880, "No such account -- nothing changed."
	*/
	exec sp_getmessage 17880, @msg output
	print @msg
	return (1)
end

/*
**  Update takes place here: column can only be fullname for C2
*/
if @column = "fullname"
begin
        update master.dbo.syslogins set fullname  = @value where suid = @suid
end
else if @column = "defdb"
begin
	execute @retstat = sybsystemprocs.dbo.sp_defaultdb @account, @value
	return (@retstat)
end
else if @column = "deflanguage"
begin
	execute @retstat = sybsystemprocs.dbo.sp_defaultlanguage @account, @value
	return (@retstat)
end

else /* error */
begin
	/*
	** 17925, "Column name invalid -- nothing changed."
	*/
	exec sp_getmessage 17925, @msg output
	print @msg
        return (1)
end

/*
**  Check @@rowcount when it works
*/
if @@rowcount = 1
begin
	/*
	** 17926, "Column changed."
	*/
	exec sp_getmessage 17926, @msg output
	print @msg
	return (0)
end
else
begin
	/*
	** 17927, "Error in changing the value of the specified column."
	*/
	exec sp_getmessage 17927, @msg output
	print @msg
	return (1)
end
go
exec sp_procxmode 'sp_modifylogin', 'anymode'
go
grant execute on sp_modifylogin to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_auditinstall')
begin
	drop procedure sp_auditinstall
end
go
print "Installing sp_auditinstall"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	5.0	1.0	06/22/92	sproc/src/auditinstall */

/*
**	Messages for sp_auditinstall
**	
**  17260, "Cant run %1! from within a transaction."
**
**  17985, "You must be in the sybsecurity database to run this procedure"
**  17986, "Device name '%1!' ignored because no segment name was provided."
**  17987, "Segment '%1!' does not exist in the sybsecurity database."
**  17988, "Creating segment '%1!' on device '%2!'..."
**  17989, "Creating sysaudits table on the '%1!' segment..."
**  17990, "Dumping transaction log in sybsecurity with no_log..."
**  18034, "The sysaudits table already exists.  This table will be
**	    truncated and re-used.  Therefore, segment and device
**	    parameters, if supplied, will be ignored."
*/

create procedure sp_auditinstall
@segname varchar(30) = "default",	/* segment for sysaudits */
@devname varchar(30) = NULL	/* device where segment is located */
as
declare @returncode	int		/* from sp_addsegment */
declare @msg 		varchar(255)	/* for sp_getmessage */

/*
**  If we're in a transaction, disallow this since it might make recovery
**  impossible.
*/
if @@trancount > 0
begin
	/* 17260, "Can't run %1! from within a transaction." */
        exec sp_getmessage 17260, @msg output
	print @msg, "sp_auditinstall"
	return (1)
end

/* check if user has sso role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/

if (proc_role("sso_role") = 0)
	return (1)

if (db_name() != "sybsecurity")
begin
	/*
	** 17985, "You must be in the sybsecurity database to run
	**	   this procedure"
	*/
	exec sp_getmessage 17985, @msg output
	print @msg
	return (-1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* Truncate an existing sysaudits. */
if exists (select * from sysobjects where name = "sysaudits")
begin
	/*
	** 18034, "The sysaudits table already exists.  This table will be
	**	   truncated and re-used.  Therefore, segment and device
	**	   parameters, if supplied, will be ignored."
	*/
	exec sp_getmessage 18034, @msg output
	print @msg
	truncate table sysaudits
	return (0)
end

/*
** If no segment name was provided, we'll build sysaudits on the
** default segment.
*/
if (@segname  = "default") or (@segname is NULL)
begin
	if (@devname is not null)
	begin
		/*
		** 17986, "Device name '%1!' ignored because no segment name 
		**	   was provided."
		*/
		exec sp_getmessage 17986, @msg output
		print @msg, @devname
	end
	select @segname = "default"
end
else
/*
** We have a segment name, so there should be a device associated
** with it.  Error if not, otherwise, we'll add the segment.
*/
begin
	if (@devname is null)
	begin
		if not exists (select * from syssegments
				where name = @segname)
		begin
			/*
			** 17987, "Segment '%1!' does not exist in
			**	   the sybsecurity database."
			*/
			exec sp_getmessage 17987, @msg output
			print @msg, @segname
			return (-2)
		end
	end
	else
	begin
		if exists (select * from syssegments where name = @segname)
			exec sp_dropsegment @segname, "sybsecurity", @devname

		/* 17988, "Creating segment '%1!' on device '%2!'..." */
		exec sp_getmessage 17988, @msg output
		print @msg, @segname, @devname
		execute @returncode =
			sp_addsegment @segname, "sybsecurity", @devname
		if (@returncode != 0)
			return (-3)
	end
end

/* 17989, "Creating sysaudits table on the '%1!' segment..." */
exec sp_getmessage 17989, @msg output
print @msg, @segname

create table sysaudits
(
	event 		smallint not null,
	eventmod 	smallint not null,
	spid 		smallint not null,
	eventtime 	datetime not null,
	sequence 	smallint not null,
	suid 		smallint not null,
	dbid 		smallint null,
	objid 		int null,
	xactid		binary(6) null,
	loginname	varchar(30) null,
	dbname		varchar(30) null,
	objname		varchar(30) null,
	objowner	varchar(30) null,

	extrainfo 	varchar(255) null
) on @segname

/* 17990, "Dumping transaction log in sybsecurity with no_log..." */
exec sp_getmessage 17990, @msg output
print @msg

dump tran sybsecurity with no_log
go
exec sp_procxmode 'sp_auditinstall', 'anymode'
go
grant execute on sp_auditinstall to sso_role
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_volchanged')
begin
	drop procedure sp_volchanged
end
go
print "Installing sp_volchanged"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */


create procedure sp_volchanged
@session_id	int,			/* session identifier		*/
@devname	varchar(255),		/* device requesting vol chg	*/
@action		varchar(255)=NULL,	/* BServer action string	*/
@fname		varchar(17)=NULL,	/* file name on device		*/
@vname		varchar(6)=NULL		/* name to init new volume with */
as

declare	@server	varchar(30)	/* server name, if network dump	*/
declare @blank	int		/* index to " " when parsing @devname	*/
declare @len	int		/* length of @devname, for parsing	*/
declare @pname	varchar(255)	/* translated physical device name	*/
declare @status	int		/* RPC status				*/


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

if (lower(@devname) like "% at %")
begin
	/*
	** <device_name> AT <host_name> -- parse the device and host
	** names into separate arguments for transmission
	*/
	select @len = datalength(@devname)
	select @blank = charindex(" ", @devname)
	select @server = ltrim(
			   substring(
			     ltrim(
			 	substring(@devname, @blank, @len)), 3, @len))
	select @devname = rtrim(substring(@devname, 1, @blank))
end
else
begin
	/* No host given -- select the local server */
	select @server = NULL

	/* and do logical name translation */
	select @pname = phyname
	from master..sysdevices
	where name = @devname
	  and (status & 16) = 16
	if (@pname is not NULL)
		select @devname = @pname
end

exec @status = SYB_BACKUP...as_volume_changed @server, @session_id,
				@devname, @action, @fname, @vname

return (@status)
go
exec sp_procxmode 'sp_volchanged', 'anymode'
go
grant execute on sp_volchanged to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_checkreswords')
begin
	drop procedure sp_checkreswords
end
go
print "Installing sp_checkreswords"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

if exists (select name from sysobjects where name = "sp_checkreswords")
	drop proc sp_checkreswords
go
/*
**Messages for "sp_checkreswords"	18035
**
** 17232, "No user with the specified name exists in the current database."
** 18035, "Reserved Words Used as Database Object Names for Database, "
** 18036, " Upgrade renames sysobjects.schema to sysobjects.schemacnt."
** 18037, " Found no reserved words used as names for database-wide objects."
** 18038, " Found no reserved words used as database object names."
*/
create procedure sp_checkreswords 
@user_name_param	varchar(30) = NULL
as

declare @msg		varchar(250)
declare @baduse_cnt	int		/* Return the count of items that */
					/* have reserved word names.	  */
declare @owner_cnt	int		/* Count of owner-based bad items */

declare @uid_param	smallint
declare @user_name	varchar(30)
declare @dbname		varchar(30)
declare	@uid		smallint

/*
** Note: do not set isolation level, because this sproc must run in
** 4.x as well as System 10.
**
** Also, do not call sp_getmessage since this sproc must run on 4.8
** which cannot support the '%1!' syntax in the print statement.
** The main side affect of this is that the messages printed out by
** this sproc are not localized.
*/

set nocount on



/*
** 18035, "Reserved Words Used as Database Object Names for Database, "
**
** NOTE:  sp_getmessage is not used for retrieving message text
** because this sproc must also run on 4.8 servers which cannot
** support the '%1!' syntax in the print statement.
*/
select @dbname = db_name()
select @msg = description from master.dbo.sysmessages
        where error = 18035
        and langid is NULL
select @msg = @msg + @dbname + "."
print @msg
print ""

select @baduse_cnt = 0

create table #uids
(
	uid		smallint NULL,
	catagory	char(1)
)

if (@user_name_param is NULL or @user_name_param = "dbo")
begin
	/*
	** 18036, " Upgrade renames sysobjects schema to sysobjects schemacnt."
	**
	** NOTE:  sp_getmessage is not used for retrieving message text
	** because this sproc must also run on 4.8 servers which cannot
	** support the '%1!' syntax in the print statement.
	*/
	select @msg = description from master.dbo.sysmessages
        	where error = 18036
        	and langid is NULL
	print @msg
	print ""
end

if (@user_name_param is not NULL)
begin
	select @uid_param = user_id(@user_name_param)
	if (@uid_param is NULL)
	begin
		/*
		** 17232, "No user with the specified name exists in the 
		**	   current database."
		**
		** NOTE:  sp_getmessage is not used for retrieving message text
		** because this sproc must also run on 4.8 servers which cannot
		** support the '%1!' syntax in the print statement.
		*/
		select @msg = description from master.dbo.sysmessages
        		where error = 17232
        		and langid is NULL
		print @msg
		return(0)
	end

	insert #uids 
		select o.uid, "c"
		from sysobjects o, master.dbo.spt_values v, syscolumns c
		where lower(c.name) = v.name and v.type = 'W' 
			and c.id = o.id 
			and o.uid = @uid_param
			and not (o.id  = 1 and c.name = "schema")
		group by o.uid
		order by o.uid

	insert #uids 
		select o.uid, "i"
		from sysobjects o, master.dbo.spt_values v, sysindexes i
		where lower(i.name) = v.name and v.type = 'W' 
			and i.id = o.id 
			and o.uid = @uid_param
			and i.indid != 0 and i.indid != 255
		group by o.uid
		order by o.uid

	insert #uids
		select o.uid, "o"
		from sysobjects o, master.dbo.spt_values v
		where lower(o.name) = v.name and v.type = 'W'  
			and o.uid = @uid_param
		group by o.uid
		order by o.uid

	insert #uids
		select t.uid, "t"
		from systypes t, master.dbo.spt_values v
		where lower(t.name) = v.name and v.type = 'W'  
			and t.uid = @uid_param
		group by t.uid
		order by t.uid
end
else
begin
	/*
	** Get the uids into a temp table.
	*/

	insert #uids 
		select o.uid, "c"
		from sysobjects o, master.dbo.spt_values v, syscolumns c
		where lower(c.name) = v.name and v.type = 'W' 
			and c.id = o.id 
			and not (o.id  = 1 and c.name = "schema")
		group by o.uid
		order by o.uid

	insert #uids 
		select o.uid, "i"
		from sysobjects o, master.dbo.spt_values v, sysindexes i
		where lower(i.name) = v.name and v.type = 'W' 
			and i.id = o.id 
			and i.indid != 0 and i.indid != 255
		group by o.uid
		order by o.uid

	insert #uids
		select o.uid, "o"
		from sysobjects o, master.dbo.spt_values v
		where lower(o.name) = v.name and v.type = 'W'  
		group by o.uid
		order by o.uid

	insert #uids
		select t.uid, "t"
		from systypes t, master.dbo.spt_values v
		where lower(t.name) = v.name and v.type = 'W'  
		group by t.uid
		order by t.uid
end

/* Not using cursors because this sproc must run in 4.x, in order for 
** clients to check their databases before upgrade.
*/

select @user_name = min(user_name(uid)) from #uids

while (@user_name is not NULL)
begin
	/* Print the owner-specific information:
	**    columns, indexes, objects(tables, sprocs, etc.), and datatypes
	*/

	select @uid = user_id(@user_name)
	select "Owner" = @user_name 

	if exists (select * from #uids
		where user_name(uid) = @user_name and catagory = "c")
	begin
		select "Table" = o.name,
			"Reserved Word Column Names " = c.name
		from sysobjects o, master.dbo.spt_values v, syscolumns c
		where lower(c.name) = v.name and v.type = 'W'
			and c.id = o.id
			and o.uid = @uid
			and not (o.id  = 1 and c.name = "schema")
		order by o.name, c.name

		select @baduse_cnt = @baduse_cnt + @@rowcount
	end

	if exists (select * from #uids
		where user_name(uid) = @user_name and catagory = "i")
	begin
		select "Table" = o.name,
			"Reserved Word Index Names" = i.name
		from sysobjects o, master.dbo.spt_values v, sysindexes i
		where lower(i.name) = v.name and v.type = 'W'
			and i.id = o.id
			and o.uid = @uid
			and i.indid != 0 and i.indid != 255
		order by o.name, i.name

		select @baduse_cnt = @baduse_cnt + @@rowcount
	end

	if exists (select * from #uids
		where user_name(uid) = @user_name and catagory = "o")
	begin
		select  "Object Type" = convert(char(30), x.name),
			"Reserved Word Object Names" = o.name
		from sysobjects o, master.dbo.spt_values v,
			master.dbo.spt_values x
		where lower(o.name) = v.name and v.type = 'W' 
			and o.uid = @uid
			and o.sysstat & 2063 = x.number
			and x.type = "O"
		order by x.name, o.name

		select @baduse_cnt = @baduse_cnt + @@rowcount
	end

	if exists (select * from #uids 
		where user_name(uid) = @user_name and catagory = "t")
	begin
		select "Reserved Word Datatype Names" = t.name
		from systypes t, master.dbo.spt_values v
		where lower(t.name) = v.name and v.type = 'W'
			and t.uid = @uid
		order by t.name

		select @baduse_cnt = @baduse_cnt + @@rowcount
	end

	/* Get next id  */
	select @user_name = min(user_name(uid)) from #uids
		where user_name(uid) > @user_name

	/* If there are more user names, print a dividing mark between them. */
	if (@user_name != NULL)
	begin
		select "-------------------------------------------------------------"
	end
end


if (@user_name_param is NULL)
begin

	select @owner_cnt = @baduse_cnt

	if (@baduse_cnt != 0)
	begin
		select "-------------------------------------------------------------"
	end
	select "Database-wide Objects" = " "

	/*
	** Print the database wide objects: users and segments
	*/

	if exists (select * from sysusers u, master.dbo.spt_values v
			where lower(u.name) = v.name and v.type = 'W'
				and u.name != "public")
	begin
		select "Reserved Word User Names" = u.name
		from sysusers u, master.dbo.spt_values v
		where lower(u.name) = v.name and v.type = 'W'
			and u.name != "public"
		order by u.name

		select @baduse_cnt = @baduse_cnt + @@rowcount
	end

	if exists (select * from syssegments s, master.dbo.spt_values v
			where lower(s.name) = v.name and v.type = 'W'
				and s.name != "default")
	begin
		select "Reserved Word Segment Names" = s.name
		from syssegments s, master.dbo.spt_values v
		where lower(s.name) = v.name and v.type = 'W'
			and s.name != "default"
		order by s.name

		select @baduse_cnt = @baduse_cnt + @@rowcount
	end


	if (db_name() = "master")
	begin
		/* Print the Server-wide information:
		**	logins, charsets, databases, and languages
		*/

		if exists (select * from master.dbo.syslogins l, 
				master.dbo.spt_values v
				where lower(l.name) = v.name and v.type = 'W')
		begin
			select "Reserved Word Login Names" = l.name
			from master.dbo.syslogins l, master.dbo.spt_values v
			where lower(l.name) = v.name and v.type = 'W'
			order by l.name

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end

		if exists (select * from master.dbo.syscharsets c, 
				master.dbo.spt_values v
				where lower(c.name) = v.name and v.type = 'W')
		begin
			select "Reserved Word Charset Names" = c.name
			from master.dbo.syscharsets c, master.dbo.spt_values v
			where lower(c.name) = v.name and v.type = 'W'
			order by c.name

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end

		if exists (select * from master.dbo.sysdatabases d, 
				master.dbo.spt_values v
				where lower(d.name) = v.name and v.type = 'W')
		begin
			select "Reserved Word Database Names" = d.name
			from master.dbo.sysdatabases d, master.dbo.spt_values v
			where lower(d.name) = v.name and v.type = 'W'
			order by d.name

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end

		if exists (select * from master.dbo.syslanguages l, 
				master.dbo.spt_values v
				where lower(l.name) = v.name and v.type = 'W')
		begin
			select "Reserved Word Language Names" = l.name
			from master.dbo.syslanguages l, master.dbo.spt_values v
			where lower(l.name) = v.name and v.type = 'W'
			order by l.name

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end

		if exists (select * from master.dbo.sysdevices d, 
				master.dbo.spt_values v
				where lower(d.name) = v.name and v.type = 'W')
		begin
			select "Reserved Word Device Names" = d.name
			from master.dbo.sysdevices d, master.dbo.spt_values v
			where lower(d.name) = v.name and v.type = 'W'
			order by d.name

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end

		if exists (select * from master.dbo.sysremotelogins r, 
							master.dbo.spt_values v
			where lower(r.remoteusername) = v.name and v.type = 'W')
		begin
			select "Reserved Word Remote Logins" = 
							r.remoteusername
			from master.dbo.sysremotelogins r, 
				master.dbo.spt_values v
			where lower(r.remoteusername) = v.name and v.type = 'W'
			order by r.remoteusername

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end

		if exists (select * from master.dbo.sysservers s, 
				master.dbo.spt_values v
			where lower(s.srvname) = v.name and v.type = 'W')
		begin
			select "Reserved Word Server Names" = s.srvname
			from master.dbo.sysservers s, master.dbo.spt_values v
			where lower(s.srvname) = v.name and v.type = 'W'
			order by s.srvname

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end

		if exists (select * from master.dbo.sysservers s, 
				master.dbo.spt_values v
			where lower(s.srvnetname) = v.name and v.type = 'W')
		begin
			select "Reserved Word ServerNetNames" = s.srvnetname
			from master.dbo.sysservers s, master.dbo.spt_values v
			where lower(s.srvnetname) = v.name and v.type = 'W'
			order by s.srvnetname

			select @baduse_cnt = @baduse_cnt + @@rowcount
		end
	end
	if (@baduse_cnt != 0 and @owner_cnt = @baduse_cnt)
	begin
		/*
		** 18037, " Found no reserved words used as names for 
		**	    database-wide objects."
		**
		** NOTE:  sp_getmessage is not used for retrieving message text
		** because this sproc must also run on 4.8 servers which cannot
		** support the '%1!' syntax in the print statement.
		*/
		select @msg = description from master.dbo.sysmessages
        		where error = 18037
        		and langid is NULL
		print @msg
	end
end


if (@baduse_cnt = 0)
begin
	/*
	** 18038, " Found no reserved words used as database object names."
	**
	** NOTE:  sp_getmessage is not used for retrieving message text
	** because this sproc must also run on 4.8 servers which cannot
	** support the '%1!' syntax in the print statement.
	*/
	select @msg = description from master.dbo.sysmessages
        	where error = 18038
        	and langid is NULL
	print @msg
end

return(@baduse_cnt)
go
go
exec sp_procxmode 'sp_checkreswords', 'anymode'
go
grant execute on sp_checkreswords to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_tables')
begin
	drop procedure sp_tables
end
go
print "Installing sp_tables"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	10.0	1.1	06/16/93	sproc/tables */

/*
** Messages for "sp_tables"         18039
**
** 17676, "This may be a temporary object. Please execute procedure from tempdb."
**
** 18039, "Table qualifier must be name of current database"
**
*/
create procedure sp_tables
@table_name		varchar(32)  = null,
@table_owner     varchar(32)  = null,
@table_qualifier varchar(32)  = null,
@table_type		varchar(100) = null
as

declare @msg varchar(90)
declare @type1 varchar(3)
declare @tableindex int

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* temp table */
if (@table_name like "#%" and
   db_name() != "tempdb")
begin
	/*
        ** Can return data about temp. tables only in tempdb
        */
        exec sp_getmessage 17676, @msg out
        print @msg
	return(1)
end

/*
** Special feature #1:	enumerate databases when owner and name
** are blank but qualifier is explicitly '%'.  
*/
if @table_qualifier = '%' and
	@table_owner = '' and
	@table_name = ''
begin	

	/*
	** If enumerating databases 
	*/
	select
		table_qualifier = name,
		table_owner = null,
		table_name = null,
		table_type = 'Database',

		/*
		** Remarks are NULL 
		*/
		remarks = convert(varchar(254),null)

		from master..sysdatabases

		/*
		** eliminate MODEL database 
		*/
		where name != 'model'
		order by table_qualifier
end

/*
** Special feature #2:	enumerate owners when qualifier and name
** are blank but owner is explicitly '%'.
*/
else if @table_qualifier = '' and
	@table_owner = '%' and
	@table_name = ''
	begin	

		/*
		** If enumerating owners 
		*/
		select distinct
			table_qualifier = null,
			table_owner = user_name(uid),
			table_name = null,
			table_type = 'Owner',

		/*
		** Remarks are NULL 
		*/
		remarks = convert(varchar(254),null)

		from sysobjects
		order by table_owner
	end
	else
	begin 

		/*
		** end of special features -- do normal processing 
		*/
		if @table_qualifier is not null
		begin
			if db_name() != @table_qualifier
			begin
				if @table_qualifier = ''
				begin  	

					/*
					** If empty qualifier supplied
					** Force an empty result set 
					*/
					select @table_name = ''
					select @table_owner = ''
				end
				else
				begin

					/*
					** If qualifier doesn't match current 
					** database. 
					*/
					exec sp_getmessage 18039, @msg out
					print @msg
					return 1
				end
			end
		end
		if @table_type is null
		begin	

			/*
			** Select all ODBC supported table types 
			*/
			select @type1 = 'SUV'
		end
		else
		begin
			/*
			** TableType are case sensitive if CS server 
			*/
			select @type1 = null

			/*
			** Add System Tables 
			*/
			if (charindex("'SYSTEM TABLE'",@table_type) != 0)
				select @type1 = @type1 + 'S'

			/*
			** Add User Tables 
			*/
			if (charindex("'TABLE'",@table_type) != 0)
				select @type1 = @type1 + 'U'

			/*
			** Add Views 
			*/
			if (charindex("'VIEW'",@table_type) != 0)
				select @type1 = @type1 + 'V'
		end
		if @table_name is null
		begin	

			/*
			** If table name not supplied, match all 
			*/
			select @table_name = '%'
		end
		else
		begin
			if (@table_owner is null) and 
			   (charindex('%', @table_name) = 0)
			begin	

			/*
			** If owner not specified and table is specified 
			*/
				if exists (select * from sysobjects
					where uid = user_id()
					and id = object_id(@table_name)
					and (type = 'U' or type = 'V' 
						or type = 'S'))
				begin	

				/*
				** Override supplied owner w/owner of table 
				*/
					select @table_owner = user_name()
				end
			end
		end

		/*
		** If no owner supplied, force wildcard 
		*/
		if @table_owner is null 
			select @table_owner = '%'
		select
			table_qualifier = db_name(),
			table_owner = user_name(o.uid),
			table_name = o.name,
			table_type = rtrim ( 
					substring('SYSTEM TABLE            TABLE       VIEW       ',
					/*
					** 'S'=0,'U'=2,'V'=3 
					*/
					(ascii(o.type)-83)*12+1,12)),

			/*
			** Remarks are NULL
			*/
			remarks = convert(varchar(254),null)

		from sysusers u, sysobjects o
		where
			/* Special case for temp. tables.  Match ids */
			(o.name like @table_name or o.id=object_id(@table_name))
			and user_name(o.uid) like @table_owner

			/*
			** Only desired types
			*/
			and charindex(substring(o.type,1,1),@type1)! = 0 

			/*
			** constrain sysusers uid for use in subquery 
			*/
			and u.uid = user_id() 
		and (
		suser_id() = 1		/* User is the System Administrator */
		or o.uid = user_id()	/* User created the object */
					/* here's the magic..select the highest
					** precedence of permissions in the
					** order (user,group,public)
					*/

		/*
		** The value of protecttype is
		**
		** 	0  for grant with grant
		**	1  for grant and,
		**	2  for revoke
		**
		** As protecttype is of type tinyint, protecttype/2 is
		** integer division and will yield 0 for both types of
		** grants and will yield 1 for revoke, i.e., when
		** the value of protecttype is 2.  The XOR (^) operation
		** will reverse the bits and thus (protecttype/2)^1 will
		** yield a value of 1 for grants and will yield a
		** value of zero for revoke.
		**
		** Normal uids have values upto 16383, roles have uids
		** from 16384 upto 16389 and uids of groups start from
		** 16390 onwards.
		**
		** If there are several entries in the sysprotects table
		** with the same Object ID, then the following expression
		** will prefer an individual uid entry over a group entry
		** and prefer a group entry over a role entry.
		**
		** For example, let us say there are two users u1 and u2
		** with uids 4 and 5 respectiveley and both u1 and u2
		** belong to a group g12 whose uid is 16390.  table t1
		** is owned by user u0 and user u0 performs the following
		** actions:
		**
		**	grant select on t1 to g12
		**	revoke select on t1 from u1
		** 
		** There will be two entries in sysprotects for the object t1,
		** one for the group g12 where protecttype = grant (1) and
		** one for u1 where protecttype = revoke (2).
		**
		** For the group g12, the following expression will
		** evaluate to:
		**
		**	(((+)*abs(16390-16383))*2) + ((1/2)^1))
		** 	= ((14) + (0)^1) = 14 + 1 = 15
		**
		** For the user entry u1, it will evaluate to:
		**
		**	(((+)*abs(4-16383)*2) + ((2/2)^1))
		**	= ((abs(-16379)*2 + (1)^1)
		**	= 16379*2 + 0 = 32758
		**
		** As the expression evaluates to a bigger number for the
		** user entry u1, select max() will chose 32758 which,
		** ANDed with 1 gives 0, i.e., sp_tables will not display
		** this particular table to the user.
		**
		** When the user u2 invokes sp_tables, there is only one 
		** entry for u2, which is the entry for the group g12, and 
		** so the group entry will be selected thus allowing the
		** table t1 to be displayed.
		**
		** Notice that multiplying by 2 makes the number an
		** even number (meaning the last digit is 0) so what
		** matters at the end is (protecttype/2)^1.
		**
		** NOTE: With fix 137148, uids have been extended into the
		** negative domain (-16383 <= uid <= +16383). For negative uids, 
		** the above expression will yield a negative number as sign(-ve)
		** yields -1 and max() will not choose this negative number.
		** To ensure that the above expression returns a positive large
		** number, we now use power(sign(uid),2) instead of sign(uid).
		**/

		or ((select max(((power(sign(uid),2)*abs(uid-16383))*2)
				+ ((protecttype/2)^1))
			from sysprotects p
			where p.id = o.id	
			/*
			** get rows for public, current users, user's groups
			*/
		      	and (p.uid = 0 or 		/* public */
			     p.uid = user_id() or 	/* current user */
			     p.uid = u.gid) 		/* users group */

			/*
			** check for SELECT, EXECUTE privilege.
			*/
		 	and (action in (193,224)))&1

			/*
			** more magic...normalise GRANT
			** and final magic...compare
			** Grants.
			*/
			) = 1)
		order by table_type, table_qualifier, table_owner, table_name
end
go
exec sp_procxmode 'sp_tables', 'anymode'
go
grant execute on sp_tables to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_special_columns')
begin
	drop procedure sp_special_columns
end
go
print "Installing sp_special_columns"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */
/*	10.0	1.0	9 JUL 93	sproc/src/special_columns */

/* 
** Messages for "sp_special_columns"
**
** 17863, "There is no table named %1! in the current database."
** 18039, "Table qualifier must be name of current database."
** 18042, "Illegal value for 'col_type' argument. Legal values are 'V' or 'R'."
**
*/

create procedure sp_special_columns (
				 @table_name		varchar(32),
				 @table_owner		varchar(32) = null,
				 @table_qualifier	varchar(32) = null,
				 @col_type		char(1) = 'R' )
as
	declare @indid			int
	declare @table_id		int
	declare @dbname			char(30)
	declare @full_table_name	char(70)
	declare @msg			char(70)

	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	/* get database name */
	select @dbname = db_name()

	/* we don't want a temp table unless we're in tempdb */
	if @table_name like "#%" and @dbname != "tempdb"
	begin	
		exec sp_getmessage 17863, @msg output
		print @msg, @table_name
		return (1)
	end

	if @table_qualifier is not null
	begin
		/* if qualifier doesn't match current database */
		if @dbname != @table_qualifier
		begin	
			exec sp_getmessage 18039, @msg output
			print @msg
			return (1)
		end
	end

	if @table_owner is null
	begin	/* if unqualified table name */
		select @full_table_name = @table_name
	end
	else
	begin	/* qualified table name */
		select @full_table_name = @table_owner + '.' + @table_name
	end

	/* get object ID */
	select @table_id = object_id(@full_table_name)

	if @col_type = 'V'
	begin /* if ROWVER, just run that query */
		select
			scope = convert(smallint, 0),
			column_name = c.name,
			data_type = d.data_type + convert(smallint,
					isnull(d.aux,
					ascii(substring("666AAA@@@CB??GG",
					2*(d.ss_dtype%35+1)+2-8/c.length,1))
					-60)),
			type_name = t.name,
			"precision" = isnull(d.data_precision,
					convert(int,c.length))
					+ isnull(d.aux, convert(int,
					ascii(substring("???AAAFFFCKFOLS",
					2*(d.ss_dtype%35+1)+2-8/c.length,1))
					-60)),
			length = isnull(d.length, convert(int,c.length))
					+ convert(int,
					isnull(d.aux,
					ascii(substring("AAA<BB<DDDHJSPP",
					2*(d.ss_dtype%35+1)+2-8/c.length, 1))
					-64)),
			scale = d.numeric_scale + convert(smallint,
					isnull(d.aux,
					ascii(substring("<<<<<<<<<<<<<<?",
					2*(d.ss_dtype%35+1)+2-8/c.length, 1))
					-60))
		from
			systypes t, syscolumns c, sybsystemprocs.dbo.spt_datatype_info d
		where
			c.id = @table_id
			and c.type = d.ss_dtype
			and c.usertype = 80	/* TIMESTAMP */
			and t.usertype = 80	/* TIMESTAMP */
		return (0)
	end

	if @col_type != 'R'
	begin
		/* 
		** msg 18042
		** Illegal value for 'col_type' argument. Legal values 
		** are 'V' or 'R'. 
		*/

		exec sp_getmessage 18042, @msg output
		print @msg
		return (1)
	end

	/* ROWID, now find the id of the 'best' index for this table */

	select @indid = (
		select min(indid)
		from sysindexes
		where
			status & 2 = 2		/* if unique index */
			and id = @table_id
			and indid > 0)		/* eliminate table row */

	 select
		scope = convert(smallint, 0),
		column_name = index_col(@full_table_name,indid,c.colid),
		data_type = d.data_type + convert(smallint,
					isnull(d.aux,
					ascii(substring("666AAA@@@CB??GG",
					2*(d.ss_dtype%35+1)+2-8/c2.length,1))
					-60)),
		type_name = rtrim(substring(d.type_name,
					1 + isnull(d.aux,
					ascii(substring("III<<<MMMI<<A<A",
					2*(d.ss_dtype%35+1)+2-8/c2.length, 1))
					-60), 13)),
		"precision" = isnull(d.data_precision, convert(int,c2.length))
					+ isnull(d.aux, convert(int,
					ascii(substring("???AAAFFFCKFOLS",
					2*(d.ss_dtype%35+1)+2-8/c2.length,1))
					-60)),
		length = isnull(d.length, convert(int,c2.length))
					+ convert(int, isnull(d.aux,
					ascii(substring("AAA<BB<DDDHJSPP",
					2*(d.ss_dtype%35+1)+2-8/c2.length, 1))
					-64)),
		scale = d.numeric_scale + convert(smallint,
					isnull(d.aux,
					ascii(substring("<<<<<<<<<<<<<<?",
					2*(d.ss_dtype%35+1)+2-8/c2.length, 1))
					-60))
	from
		sysindexes x,
		syscolumns c,
		sybsystemprocs.dbo.spt_datatype_info d,
		systypes t,
		syscolumns c2	/* self-join to generate list of index
				** columns and to extract datatype names */
	where
		x.id = @table_id
		and c2.name = index_col(@full_table_name, @indid,c.colid)
		and c2.id =x.id
		and c.id = x.id
		and c.colid < keycnt + (x.status & 16) / 16
		and x.indid = @indid
		and c2.type = d.ss_dtype
		and c2.usertype *= t.usertype

	return (0)
go
go
exec sp_procxmode 'sp_special_columns', 'anymode'
go
grant execute on sp_special_columns to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_columns')
begin
	drop procedure sp_columns
end
go
print "Installing sp_columns"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G% " */
/*      10.0        07/20/93        sproc/columns */
 

/* This is the version for servers which support UNION */

/* This routine is intended for support of ODBC connectivity.  Under no
** circumstances should changes be made to this routine unless they are
** to fix ODBC related problems.  All other users are at there own risk!
**
** Please be aware that any changes made to this file (or any other ODBC
** support routine) will require Sybase to recertify the SQL server as
** ODBC compliant.  This process is currently being managed internally
** by the "Interoperability Engineering Technology Solutions Group" here
** within Sybase.
*/

CREATE PROCEDURE sp_columns (
				 @table_name		varchar(32),
				 @table_owner		varchar(32) = null,
				 @table_qualifier	varchar(32) = null,
				 @column_name		varchar(32) = null )
AS
    declare @msg    		varchar(250)
    declare @full_table_name    char(70)
    declare @table_id int

    if @column_name is null /*	If column name not supplied, match all */
	select @column_name = '%'

    /* Check if the current database is the same as the one provided */
    if @table_qualifier is not null
    begin
		if db_name() != @table_qualifier
		begin	/* 
			** If qualifier doesn't match current database 
			** 18039, Table qualifier must be name of current database
			*/
                        exec sp_getmessage 18039, @msg output
                        print @msg
                        return (1)

		end
    end

    if @table_name is null
    begin	/*	If table name not supplied, match all */
		select @table_name = '%'
    end

    if @table_owner is null
    begin	/* If unqualified table name */
		SELECT @full_table_name = @table_name
    end
    else
    begin	/* Qualified table name */
		SELECT @full_table_name = @table_owner + '.' + @table_name
    end

    /* Get Object ID */
    SELECT @table_id = object_id(@full_table_name)


    /* If the table name parameter is valid, get the information */ 
    if ((charindex('%',@full_table_name) = 0) and
		(charindex('_',@full_table_name) = 0)  and
		@table_id != 0)
    begin
		/* 
		** This block is for the case where there is no pattern
		** matching required for the table name
		*/
		SELECT	/* INTn, FLOATn, DATETIMEn and MONEYn types */
			table_qualifier = DB_NAME(),
			table_owner = USER_NAME(o.uid),
			table_name = o.name,
			column_name = c.name,
			data_type = d.data_type+convert(smallint,
						isnull(d.aux,
						ascii(substring("666AAA@@@CB??GG",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))
						-60)),
			type_name = rtrim(substring(d.type_name,
						1+isnull(d.aux,
						ascii(substring("III<<<MMMI<<A<A",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60), 13)),
			"precision" = isnull(convert(int, c.prec),
				         isnull(convert(int, d.data_precision),
					        convert(int,c.length)))
						+isnull(d.aux, convert(int,
						ascii(substring("???AAAFFFCKFOLS",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))-60)),
			length = isnull(convert(int, c.length), 
				        convert(int, d.length)) +
					   convert(int, isnull(d.aux,
						ascii(substring("AAA<BB<DDDHJSPP",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-64)),
			scale = isnull(convert(smallint, c.scale), 
				       convert(smallint, d.numeric_scale))
						+convert(smallint,
						isnull(d.aux,
						ascii(substring("<<<<<<<<<<<<<<?",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60)),
			radix = d.numeric_radix,
			nullable =	/* set nullability from status flag */
				convert(smallint, convert(bit, c.status&8)),
			remarks = convert(varchar(254),null),	/* Remarks are NULL */
			ss_data_type = c.type,
			colid = c.colid
		FROM
			syscolumns c,
			sysobjects o,
			sybsystemprocs.dbo.spt_datatype_info d,
			systypes t
		WHERE
			o.id = @table_id
			AND c.id = o.id
			/*
			** We use syscolumn.usertype instead of syscolumn.type
			** to do join with systypes.usertype. This is because
			** for a column which allows null, type stores its
			** Server internal datatype whereas usertype still
			** stores its user defintion datatype.  For an example,
			** a column of type 'decimal NULL', its usertype = 26,
			** representing decimal whereas its type = 106 
			** representing decimaln. nullable in the select list
			** already tells user whether the column allows null.
			** In the case of user defining datatype, this makes
			** more sense for the user.
			*/
			AND c.usertype = t.usertype
			AND t.type = d.ss_dtype
			AND c.name like @column_name
			AND d.ss_dtype IN (111, 109, 38, 110)	/* Just *N types */
			AND c.usertype < 100		/* No user defined types */
		UNION
		SELECT	/* All other types including user data types */
			table_qualifier = DB_NAME(),
			table_owner = USER_NAME(o.uid),
			table_name = o.name,
			column_name = c.name,
			data_type = d.data_type+convert(smallint,
						isnull(d.aux,
						ascii(substring("666AAA@@@CB??GG",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))
						-60)),
			type_name = rtrim(substring(d.type_name,
						1+isnull(d.aux,
						ascii(substring("III<<<MMMI<<A<A",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60), 13)),
			"precision" = isnull(convert(int, c.prec),
					 isnull(convert(int, d.data_precision), 
						convert(int,c.length)))
						+isnull(d.aux, convert(int,
						ascii(substring("???AAAFFFCKFOLS",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))-60)),
			length = isnull(convert(int, c.length), 
					convert(int, d.length)) +
					   convert(int, isnull(d.aux,
						ascii(substring("AAA<BB<DDDHJSPP",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-64)),
			scale = isnull(convert(smallint, c.scale), 
				       convert(smallint, d.numeric_scale)) +
						convert(smallint, isnull(d.aux,
						ascii(substring("<<<<<<<<<<<<<<?",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60)),
			radix = d.numeric_radix,
			nullable =	/* set nullability from status flag */
				convert(smallint, convert(bit, c.status&8)),
			remarks = convert(varchar(254),null),	/* Remarks are NULL */
			ss_data_type = c.type,
			colid = c.colid
		FROM
			syscolumns c,
			sysobjects o,
			sybsystemprocs.dbo.spt_datatype_info d,
			systypes t
		WHERE
			o.id = @table_id
			AND c.id = o.id
			/*
			** We use syscolumn.usertype instead of syscolumn.type
			** to do join with systypes.usertype. This is because
			** for a column which allows null, type stores its
			** Server internal datatype whereas usertype still
			** stores its user defintion datatype.  For an example,
			** a column of type 'decimal NULL', its usertype = 26,
			** representing decimal whereas its type = 106 
			** representing decimaln. nullable in the select list
			** already tells user whether the column allows null.
			** In the case of user defining datatype, this makes
			** more sense for the user.
			*/
			AND c.usertype = t.usertype
			/*
			** We need a equality join with 
			** sybsystemprocs.dbo.spt_datatype_info here so that
			** there is only one qualified row returned from 
			** sybsystemprocs.dbo.spt_datatype_info, thus avoiding
			** duplicates.
			*/
			AND t.type = d.ss_dtype
			AND c.name like @column_name
			AND (d.ss_dtype NOT IN (111, 109, 38, 110) /* No *N types */

				OR c.usertype >= 100) /* User defined types */

			 ORDER BY colid
	end
	else
    begin
		/* 
		** This block is for the case where there IS pattern
		** matching done on the table name. 
		*/
		if @table_owner is null /* If owner not supplied, match all */
			select @table_owner = '%'

		SELECT	/* INTn, FLOATn, DATETIMEn and MONEYn types */
			table_qualifier = DB_NAME(),
			table_owner = USER_NAME(o.uid),
			table_name = o.name,
			column_name = c.name,
			data_type = d.data_type+convert(smallint,
						isnull(d.aux,
						ascii(substring("666AAA@@@CB??GG",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))
						-60)),
			type_name = rtrim(substring(d.type_name,
						1+isnull(d.aux,
						ascii(substring("III<<<MMMI<<A<A",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60), 13)),
			"precision" = isnull(convert(int, c.prec),
					  isnull(convert(int, d.data_precision),
					         convert(int, c.length)))
						+isnull(d.aux, convert(int,
						ascii(substring("???AAAFFFCKFOLS",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))-60)),
			length = isnull(convert(int, c.length), 
					convert(int,d.length)) +
					   convert(int, isnull(d.aux,
						ascii(substring("AAA<BB<DDDHJSPP",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-64)),
			scale = isnull(convert(smallint, c.scale), 
				       convert(smallint, d.numeric_scale)) +
						convert(smallint, isnull(d.aux,
						ascii(substring("<<<<<<<<<<<<<<?",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60)),
			radix = d.numeric_radix,
			nullable =	/* set nullability from status flag */
				convert(smallint, convert(bit, c.status&8)),
			remarks = convert(varchar(254),null),	/* Remarks are NULL */
			ss_data_type = c.type,
			colid = c.colid
		FROM
			syscolumns c,
			sysobjects o,
			sybsystemprocs.dbo.spt_datatype_info d,
			systypes t
		WHERE
			o.name like @table_name
			AND user_name(o.uid) like @table_owner
			AND o.id = c.id
			/*
			** We use syscolumn.usertype instead of syscolumn.type
			** to do join with systypes.usertype. This is because
			** for a column which allows null, type stores its
			** Server internal datatype whereas usertype still
			** stores its user defintion datatype.  For an example,
			** a column of type 'decimal NULL', its usertype = 26,
			** representing decimal whereas its type = 106 
			** representing decimaln. nullable in the select list
			** already tells user whether the column allows null.
			** In the case of user defining datatype, this makes
			** more sense for the user.
			*/
			AND c.usertype = t.usertype
			AND t.type = d.ss_dtype
			AND o.type != 'P'
			AND c.name like @column_name
			AND d.ss_dtype IN (111, 109, 38, 110)	/* Just *N types */
			AND c.usertype < 100
		UNION
		SELECT /* All other types including user data types */
			table_qualifier = DB_NAME(),
			table_owner = USER_NAME(o.uid),
			table_name = o.name,
			column_name = c.name,
			data_type = d.data_type+convert(smallint,
						isnull(d.aux,
						ascii(substring("666AAA@@@CB??GG",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))
						-60)),
			type_name = rtrim(substring(d.type_name,
						1+isnull(d.aux,
						ascii(substring("III<<<MMMI<<A<A",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60), 13)),
			"precision" = isnull(convert(int, c.prec),
					  isnull(convert(int, d.data_precision),
						 convert(int,c.length)))
						+isnull(d.aux, convert(int,
						ascii(substring("???AAAFFFCKFOLS",
						2*(d.ss_dtype%35+1)+2-8/c.length,1))-60)),
			length = isnull(convert(int, c.length), 
					convert(int, d.length)) +
					   convert(int, isnull(d.aux,
						ascii(substring("AAA<BB<DDDHJSPP",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-64)),
			scale = isnull(convert(smallint, c.scale),
				       convert(smallint, d.numeric_scale)) +
						convert(smallint, isnull(d.aux,
						ascii(substring("<<<<<<<<<<<<<<?",
						2*(d.ss_dtype%35+1)+2-8/c.length,
						1))-60)),
			radix = d.numeric_radix,
			nullable =	/* set nullability from status flag */
				convert(smallint, convert(bit, c.status&8)),
			remarks  = convert(varchar(254),null),
			ss_data_type = c.type,
			colid = c.colid
		FROM
			syscolumns c,
			sysobjects o,
			sybsystemprocs.dbo.spt_datatype_info d,
			systypes t
		WHERE
			o.name like @table_name
			AND user_name(o.uid) like @table_owner
			AND o.id = c.id
			/*
			** We use syscolumn.usertype instead of syscolumn.type
			** to do join with systypes.usertype. This is because
			** for a column which allows null, type stores its
			** Server internal datatype whereas usertype still
			** stores its user defintion datatype.  For an example,
			** a column of type 'decimal NULL', its usertype = 26,
			** representing decimal whereas its type = 106 
			** representing decimaln. nullable in the select list
			** already tells user whether the column allows null.
			** In the case of user defining datatype, this makes
			** more sense for the user.
			*/
			AND c.usertype = t.usertype
			/*
			** We need a equality join with 
			** sybsystemprocs.dbo.spt_datatype_info here so that
			** there is only one qualified row returned from 
			** sybsystemprocs.dbo.spt_datatype_info, thus avoiding
			** duplicates.
			*/
			AND t.type = d.ss_dtype
			AND c.name like @column_name
			AND o.type != 'P'
			AND c.name like @column_name
			AND (d.ss_dtype NOT IN (111, 109, 38, 110) /* No *N types */

				OR c.usertype >= 100) /* User defined types */

		ORDER BY table_owner, table_name, colid
	end
	
	return(0)
go
go
exec sp_procxmode 'sp_columns', 'anymode'
go
grant execute on sp_columns to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_aux_parse_entity')
begin
	drop procedure sp_aux_parse_entity
end
go
print "Installing sp_aux_parse_entity"
go

/*
** Auxilliary stored procedure for parsing entities.  Entities
** may either be databases, tables, or indices.
**
** The following assumptions will be made:
**	1) If the database parameter is NULL, it is assumed that the entity
**	   being addressed belongs in the current database.
**
** Input Parameters:
**	dbname		database name (NULL if none specified)
**	tablename	NULL if no table is being specified
**				(Note that this indicates that the entity
**				 is a database.  This also requires that
**				 the indexname parameter be NULL.)
**			table name otherwise
**				(specified in the following format:
**					`[owner_name.]table_name'
**				 Note that database name is not accepted.)
**	indexname	NULL or "table only" if index not being specified
**			"text only" if specifying text/image pages only
**			name of index otherwise
** 
** Output parameters:
**	dbid		database id
**	ownerid		user id of owner of entity
**	objid		NULL if no table specified
**			object id otherwise
**	indid		NULL if no index specified
**			index id otherwise (index id 255 used to specify
**			text/image pages)
**	entitytype	`D' for databases
**			`T' for tables
**			`I' for indices
** Returns:
**	0		everything went ok
**	1		general error
**	2		syntax error - raising a usage message is
**			*REQUIRED* after one of these.
*/

/*
** Messages for "sp_aux_parse_entity"
**
** 17460, "Object must be in the current database."
** 18088, "The target database does not exist."
** 18090, "The target object does not exist."
** 18091, "The target index does not exist."
** 18154, "`%1!' is not a table."
** 18171, "The table must have a text column if `text only' is specified."
*/

create procedure sp_aux_parse_entity
@dbname		varchar(30) = NULL,
@tablename	varchar(62) = NULL,
@indexname	varchar(30) = NULL,
@dbid		int output,
@ownerid	int output,
@objid		int output,
@indid		int output,
@entitytype	char(1)	output
as

declare @tablestring	varchar(92)
declare @objecttype	char(2)
declare @msg		varchar(255)

select @dbid		= NULL
select @ownerid		= NULL
select @objid		= NULL
select @indid		= NULL
select @entitytype	= NULL

/*
** Perform generic syntax checks on the arguments.
*/
if	(@dbname like "%.%")
	or (@indexname like "%.%")
	or (@tablename like ".%")
	or (@tablename like "%.")
	or (@tablename like "%.%.%")
begin
	/*
	** No need for us to raise a syntax error message here.
	** Let the caller raise an error message for us.
	*/
	return 2
end

/*
** Check for a database entity
*/
if @tablename = NULL
begin
	/*
	** Syntax error checking.
	*/
	if @dbname = NULL
	begin
		/*
		** No need for us to raise a syntax error message here.
		** Let the caller raise an error message for us.
		*/
		return 2
	end

	if @indexname != NULL
	begin
		/*
		** No need for us to raise a syntax error message here.
		** Let the caller raise an error message for us.
		*/
		return 2
	end

	/*
	** This is a database entity.  See if the database exists.
	*/
	select @dbid = db_id(@dbname)
	if @dbid = NULL
	begin
		exec sp_getmessage 18088, @msg output
		print @msg
		return 1
	end

	/*
	** Set the output parameters and return
	*/
	select @ownerid		= user_id("dbo")
	select @entitytype	= 'D'
end
else
begin
	/*
	** The entity is either a table or an index.
	*/

	/*
	** In both instances we need to figure out the table id.
	** In order to do this, first, make sure we are only affecting
	** objects in the current database!
	*/
	if @dbname != NULL
	begin
		if @dbname != db_name()
		begin
			exec sp_getmessage 17460, @msg output
			print @msg
			return 1
		end
	end
	else
	begin
		select @dbname = db_name()
	end

	select @dbid = db_id()

	/*
	** Next, formulate the fully-qualified table name.
	*/
	if @tablename like "%.%"
	begin
		select @tablestring = @dbname + "." + @tablename
	end
	else
	begin
		select @tablestring = @dbname + "." + user_name() +"." +
				      @tablename
	end

	/*
	** Retrieve the id from the fully-qualified table name.
	*/
	select @objid = object_id(@tablestring)

	/*
	** Check for existence.
	*/
	if @objid = NULL
	begin
		exec sp_getmessage 18090, @msg output
		print @msg
		return 1
	end

	/*
	** Retrieve the owner and type of this object.  Make sure that 
	** the object is indeed a table.
	*/
	select @ownerid = uid, @objecttype = type
	from sysobjects
	where (id = @objid)

	if (@objecttype != 'S') and (@objecttype != 'U')
	begin
		exec sp_getmessage 18154, @msg output
		print @msg, @tablestring
		return 1
	end

	/*
	** Now handle the index special case, if any.
	*/
	if (@indexname != NULL) and (lower(@indexname) != "table only")
	begin
		/*
		** An index has been specified.  Check for the special
		** "text only" case.
		*/
		if lower(@indexname) = "text only"
		begin
			/*
			** Check if the table has a text/image column.
			*/
			if not exists (select *
				       from sysindexes
				       where	(indid = 255) and
					     	(id = @objid))
			begin
				exec sp_getmessage 18171, @msg output
				print @msg
				return 1
			end
			else
			begin
				select @indid = 255
			end
		end
		else
		begin
			/*
			** Grab the index id.
			*/
			select @indid = indid from sysindexes
			where (id = @objid) and (name = @indexname)

			/*
			** Check for existence.
			*/
			if @indid = NULL
			begin
				exec sp_getmessage 18091, @msg output
				print @msg
				return 1
			end
		end
		select @entitytype = 'I'
	end
	else
	begin
		select @entitytype = 'T'
	end
end

return 0
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_cachestrategy')
begin
	drop procedure sp_cachestrategy
end
go
print "Installing sp_cachestrategy"
go

/*
** 18173, "Only the System Administrator (SA) or the Object Owner
**	   may execute this stored Procedure."
** 18176, "Usage: sp_cachestrategy dbname [, [ownername.]tablename
**	   [, indexname | `text only' | `table only'
**	   [, prefetch | mru, `on' | `off']]]"
*/

/* 
** This procedure sets a default prefetch strategy for a given object.
** For non-clustered index it only affects its index pages.
** For clustered indexes it affects the data pages as well.
*/
CREATE PROCEDURE sp_cachestrategy
@dbname 	varchar(30),
@tablename 	varchar(30),
@indexname 	varchar(30) = NULL,
@strategy	varchar(30) = NULL,
@onoff		varchar(4)  = NULL
AS

DECLARE @stat2	 	int
DECLARE @dbid	 	int
DECLARE @ownerid 	int
DECLARE @tabid	 	int
DECLARE @indid	 	int
DECLARE @entitytype	char(1)
DECLARE @status		int
DECLARE @updated	int
DECLARE @indname	varchar(30)
DECLARE @largeio	varchar(8)
DECLARE @bufstr		varchar(8)
DECLARE @msg		varchar(255)


IF @@trancount = 0
BEGIN
	SET chained off
END

SET transaction isolation level 1

SELECT	@stat2 = 0

IF @dbname IS NULL
BEGIN
	/*
	** The database name is required for this stored procedure.
	*/
	EXEC	sp_getmessage 18176, @msg OUT
	PRINT	@msg
	RETURN	(1)
END

/*
** Retrieve the id's required to identify the object affected
*/
SELECT @status		= 0
SELECT @dbid		= NULL
SELECT @ownerid		= NULL
SELECT @tabid		= NULL
SELECT @indid		= NULL
SELECT @entitytype	= NULL
EXEC @status = sp_aux_parse_entity @dbname, @tablename, @indexname,
				   @dbid OUTPUT, @ownerid OUTPUT,
				   @tabid OUTPUT, @indid OUTPUT,
				   @entitytype OUTPUT
IF @status = 2
BEGIN
	/*
	** A syntax error was encountered.  Raise a usage message.
	*/
	EXEC	sp_getmessage 18176, @msg OUT
	PRINT	@msg
	RETURN	(1)
END
ELSE IF @status != 0
BEGIN
	RETURN (@status)
END

/*
**  Perform permission checks.  Basically, only the System Administrator
**  can change the cache strategy for objects he/she doesn't own.
*/
IF @ownerid != user_id() 
BEGIN
	/*
	** Check if the user has the SA role.
	*/
	IF proc_role("sa_role") = 0
	BEGIN
		/*
		** proc_role already raised an error message but we want
		** to supply an addendum saying that you need to be the
		** owner of the object in order to perform this operation.
		*/
		EXEC	sp_getmessage 18173, @msg OUT
		PRINT	@msg
		RETURN	(1)
	END
END

/*
**  Fix the index id if the entity is a table.
*/
IF (@entitytype = 'T')
BEGIN
	/*
	** Leaf level of clustered index, if it exists,
	** contain the data pages
	*/
	SELECT @indid = 1

	IF NOT EXISTS (SELECT *
		       FROM   sysindexes
		       WHERE  id = @tabid AND indid = 1)
	BEGIN
		SELECT @indid = 0
	END
END

IF (@strategy != NULL)
	AND (lower(@strategy) NOT IN ("prefetch", "mru"))
	AND ((@onoff = NULL)
		OR (lower(@onoff) NOT IN ("on", "off")))
BEGIN
	/*
	** A syntax error was encountered.  Raise a usage message.
	*/
	EXEC	sp_getmessage 18176, @msg OUT
	PRINT	@msg
	RETURN	(1)
END

/*
** Initialize some variables.
*/
SELECT @stat2 = status2, @indname = name
FROM   sysindexes
WHERE  id = @tabid AND indid = @indid

SELECT @updated = 0

/*
**  Check if invoking the precedure in informational mode
**  In this case the user may not specify any strategy.
*/
IF (@onoff = NULL)
BEGIN
	/* Print the SHOWPLAN messages here as well */
	IF (@stat2 & 16 = 16)
		SELECT @largeio = "OFF"
	ELSE
		SELECT @largeio = "ON"

	IF (@stat2 & 32 = 32)
		SELECT @bufstr = "OFF"
	ELSE
		SELECT @bufstr = "ON"

	SELECT  "object name" = user_name(@ownerid) + "." +
				object_name(@tabid),
		"index name"  = @indname,
		"large IO"    = @largeio,
		"MRU"         = @bufstr

	RETURN(0)
END

/*
** Turn the sysindexes.status2 field for IND2_NOPREFETCH
*/
IF lower(@strategy) = "prefetch"
BEGIN
	IF lower(@onoff) = "off"
	BEGIN
		IF (@stat2 & 16) = 0
		BEGIN
			UPDATE sysindexes
			SET    status2 = status2 | 16
			WHERE  id = @tabid AND indid = @indid

			SELECT @updated =  1
		END
	END
	ELSE
	BEGIN
		IF (@stat2 & 16) != 0
		BEGIN
			UPDATE sysindexes
			SET    status2 = status2 & -17
			WHERE  id = @tabid AND indid = @indid

			SELECT @updated = 1
		END
	END
END
ELSE	/* Already checked for all legal values, must be MRU now */
BEGIN
	IF lower(@onoff) = "off"
	BEGIN
		IF (@stat2 & 32) = 0
		BEGIN
			UPDATE sysindexes
			SET    status2 = status2 | 32
			WHERE  id = @tabid AND indid = @indid

			SELECT @updated = 1
		END
	END
	ELSE
	BEGIN
		IF (@stat2 & 32) != 0
		BEGIN
			UPDATE sysindexes
			SET    status2 = status2 & -33
			WHERE  id = @tabid AND indid = @indid

			SELECT @updated = 1
		END
	END
END

/*
** We need to increment the object's schema count if we changed
** its cache strategy.
*/
IF @updated = 1
BEGIN
	UPDATE sysobjects
		SET schemacnt = schemacnt + 1
		FROM sysobjects
		WHERE (id = @tabid) AND (schema_inc(@tabid) IS NULL)
END

RETURN(0)
go
exec sp_procxmode 'sp_cachestrategy', 'anymode'
go
grant execute on sp_cachestrategy to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */

use sybsystemprocs
go

if not exists (select *
                from sysusers
                        where name = "guest")
begin
        execute sp_adduser guest,guest
end
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_chgattribute')
begin
	drop procedure sp_chgattribute
end
go
print "Installing sp_chgattribute"
go

/* Sccsid = "@(#) generic/sproc/chgattribute 1.1 4/6/95 " */

/*
** Messages for "sp_chgattribute"
**
** 17260, "Can't run %1! from within a transaction."
** 17460, "Object must be in the current database."
** 17782, "You do not own a table or column (or index) of that name in the current database."
** 18121, "Unrecognized change attribute option."
** 18122, "'%1!' attribute of object '%2!' changed to %3!."
** 18181, "The option max_rows_per_page is not allowed on text/image objects."
**
*/

create procedure sp_chgattribute
@objname varchar(92),                   /* table or index name */
@optname varchar(30),
@optvalue int
as

declare @objid int                      /* object id of the table */
declare @indid int                      /* table's index id  */
declare @msg varchar(250)

/* If we're in a transaction, disallow this */
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_chgattribute"
        return (1)
end
else
begin
        set chained off
end

set transaction isolation level 1

if @objname like "%.%.%"
begin
        /*
        ** 17460, "Object must be in the current database."
        */
        exec sp_getmessage 17460, @msg output
        print @msg
        return (1)
end

if not exists (
	select * from master.dbo.spt_values 
		 where type = "H"
		 and  name = @optname)
begin
        /*
        ** 18121, "Unrecognized change attribute option."
        */
        exec sp_getmessage 18121, @msg output
        print @msg
	return (1)
end

if @optname = "max_rows_per_page"
begin

	/* 
	** Change required in the max_rows_per_page value of the table/index. 
	*/

	begin transaction

	declare @tabname varchar(30)            /* name of table */
	declare @indname varchar(30)            /* name of index */
	declare @newlimit smallint		/* New max rows per page val */

	if @objname like "%.%"
	begin

		/*
		**  Get the table name and index name out.
		*/
		select @tabname = substring(@objname, 1, charindex(".", @objname) - 1)
		select @indname = substring(@objname, charindex(".", @objname) + 1, 61)


		select @objid = sysindexes.id, @indid = sysindexes.indid
			from sysobjects, sysindexes
		where 	sysindexes.id = sysobjects.id
			and sysobjects.name = @tabname
			and sysindexes.name = @indname
			and sysindexes.indid != 0
			and sysobjects.sysstat & 7 = 3  /* user table */
			and sysobjects.uid = user_id()

	end
	else
	begin
		select @tabname = @objname
		select @objid = sysobjects.id, @indid=sysindexes.indid
			from sysobjects, sysindexes
		where 	sysobjects.name = @tabname
			and sysindexes.id = sysobjects.id
			and sysindexes.indid in (0,1)
			and sysobjects.sysstat & 7 = 3  /* user table */
			and sysobjects.uid = user_id()
	end
	/*
	**  If @objid is still NULL then that means it isn't an
	**  index name.  
	*/
	if (@objid is null)
	begin
		/*
		** 17782, "You do not own a table, column or index of that name in 
		** the current database."
		*/
		exec sp_getmessage 17782, @msg output
		print @msg
		rollback transaction
		return (1)
	end

	/*
	** Disallow "max_rows_per_page" on text/image index.
	*/
	if (@indid = 255)
	begin
		/*
		** 18181, "The option max_rows_per_page is not allowed
		** on text/image objects."
		*/
		exec sp_getmessage 18181, @msg output
		print @msg
		rollback transaction
		return (1)
	end

	select @newlimit = convert(smallint, @optvalue)

	/*
	**  Go ahead and change the maxrowsperpage value in sysindexes.
	*/
	update sysindexes
		set maxrowsperpage = @newlimit
			from sysindexes
		where id = @objid
			and indid = @indid

	/*
	** If there was an error, @@error will be non-zero
	*/
	if @@error != 0
	begin
		if @@trancount != 0
			rollback transaction
		return (1)
	end

	/* 
	** update the cache.
	*/

	dbcc chgmaxrowsperpg(@tabname, @indid, @newlimit)

	/*
	** If there was an error, @@error will be non-zero
	*/
	if @@error != 0
	begin
		if @@trancount != 0
			rollback transaction
		return (1)
	end


	commit transaction
end

/*
** 18122, "'%1!' attribute of object '%2!' changed to %3!."
*/
exec sp_getmessage 18122, @msg output
print @msg,@optname, @objname,@optvalue

return (0)
go
exec sp_procxmode 'sp_chgattribute', 'anymode'
go
grant execute on sp_chgattribute to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_cacheconfig')
begin
	drop procedure sp_cacheconfig
end
go
print "Installing sp_cacheconfig"
go

/* This stored procedure is for configuring named caches.
**
**	Messages for sp_cacheconfig
**
** 17260, "Can't run %1! from within a transaction."
** 18135, "The specified named cache (%1) does not exist"
**
** 18136, "The cache type can only be spcified once."
**
** 18137, "Attempt to delete the default data cache.  The default cache may not
**	   be deleted."
**
** 18140, "Cannot modify a cache type to be 'log only' when non-log objects 
**         are bound to it. Use sp_helpcache to print out bound objects 
**	   and sp_unbindcache to delete the cache bindings."
**
** 18155, "The cache type can be either 'logonly' or 'mixed' only."
**
** 18172, "The change is completed. The SQL Server must be rebooted for the
**	   change to take effect."
**
** 18177, "Usage: sp_cacheconfig [ cachename [, 'cache_size[K|P|M|G]' ]
**	   [, logonly | mixed ]]"
*/
create procedure sp_cacheconfig
@cachename 	varchar(30) = "%",
@parm1		varchar(30) = NULL,
@parm2		char(10) = NULL
as
/*
**  The following variable are used to print out cache configuration 
**  information.
*/
declare @print_str	varchar(255)	/* for printing error msgs */
declare	@sysconf_name	varchar(255)	/* cache name from sysconfigures */
declare @io_sz_comment	char(255)	/* io size string from sysconfigures */
declare @cache_type	char(11)	/* cache type from sysconfigures */
declare	@stat_to_print	char(10)	/* status string from sysconfigures */
declare @pool_status	char(21)	/* status of pool */
declare @config_sz_str	char(13)	/* configured sz from sysconfigures */
declare @run_sz_str	char(13)	/* run size from sysconfigures */
declare @io_sz_str	varchar(3)	/* pool size (in KB) */
declare @wash_sz_str	char(10)	/* wash size of a pool */
declare @operation	int		/* update, insert, or delete */
declare @config		int		/* config value from sysconfigures */
declare @size		int		/* generic size of a cache or pool */
declare @row_count	int		/* # cache/pool rows in sysconfigures */
declare @cache_count	int		/* # cache rows in sysconfigures */
declare	@ret		int		/* return value from sp_aux_getsize */
declare @wash_size	int		/* wash size of a pool */
declare	@run_size	int		/* run_size of a pool or cache */
declare	@config_size	int		/* config size of a pool or cache */
declare @total_cfg_sz 	float		/* total, all configured cache mem */
declare @total_run_sz	float		/* total, all run cache mem */
declare	@stat		smallint	/* status from sysconfigures */
declare	@old_stat	smallint	/* status before update of sysconf. */
declare	@new_cache_type smallint	/* modified value of cache type */
declare @dflt_ctype 	smallint	/* default cache type when unspecified */
declare @mincachename varchar(30)	/* for looping through temp table */
declare @print_reboot_msg varchar(10) 	/* whether to print reboot message */
declare @pools_available int		/* whether all pools are available */


/* Dont allow sp_cacheconfig to run with in a transaction */
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @print_str output
	print @print_str, "sp_cacheconfig"
	return (1)
end
else
begin
	set transaction isolation level 1
	set chained off
	set nocount on
end

if @parm1 = NULL and @parm2 = NULL
begin
	/*
	** Create temp tables to store cache information
	** and pool information
	*/
	create table #cache_info	(
		cache_name varchar(30),
		Status varchar(9),
		Type  	varchar(8),
		configval	char(12),
		runval  	char(12))
	create table #pool_detail (
		cache_name varchar(30),
		io_sz varchar(8), 
		wash_size varchar(9),
		configval	char(12),
		runval  	char(12),
		pool_status	char(21))

	/*
	**  Create temp table with just those rows from sysconfigures that have
	**  to do with cache configuration.
	*/
	select co.config, parent, convert(char(30), co.name) name, 
		co.value config_size, co.status, 
		convert(char(30),co.comment) comment, cu.value run_size, 
		memory_used wash_size
	into #syscacheconfig
	from master.dbo.sysconfigures co, master.dbo.syscurconfigs cu
	where parent = 19
		and co.config = cu.config
		and co.name = cu.comment
		and name like "%" + @cachename + "%"
	order by name, config
	/*
	** Add rows for pending configurations
	*/
	insert #syscacheconfig 
		select co.config, parent, convert(char(30), co.name) name, 
			co.value config_size, co.status, 
			convert(char(30),co.comment) comment, 0, 0
		from master.dbo.sysconfigures co
		where parent = 19 
			and status&64 = 64  
			and name like "%" + @cachename + "%"
		
	/*
	** Determine the number of caches
	*/
	select @cache_count = count(*) 
		from #syscacheconfig where config = 19

	/*
	**  If no rows qualify then this cache doesn't exist.
	*/
	if @cache_count = 0
	begin
		select @cachename = rtrim(@cachename)
		exec sp_getmessage 18135, @print_str output
		print @print_str, @cachename
		return(1)
	end

	/*
	** Determine the total number of caches, and pools within caches.
	*/
	select @row_count = count(*) 
		from #syscacheconfig where parent = 19

	/*
	**  Intialize total configured and run sizes.
	*/	
	select @total_cfg_sz = 0, @total_run_sz = 0

	/* Until determined otherwise, all defined pools are available */
	select @pools_available = 1

	declare sysc_cursor cursor
	for select config, config_size, name, status, comment, run_size, wash_size
		from #syscacheconfig
 
	open sysc_cursor

	while (@row_count > 0)
	begin
		fetch sysc_cursor into @config, @config_size, @sysconf_name, 
				@stat, @io_sz_comment , @run_size, @wash_size

		/*
		**  A config value of 19 means this rows holds the total size
		**  and type information for the whole cache.
		*/
		if @config = 19
		begin
			/*
			** Check to see if this cache is actively running, 
			** has been created but the server has not been 
			** re-booted so it hasn't been instantiated, or it's 
			** been deleted and still occupying memory because 
			** the server has not been rebooted yet.
			*/
			if (@stat & 32 = 32)
			begin
				select @stat_to_print = "Active"
			end
			if (@stat & 64 = 64)
			begin
				select @stat_to_print = "Pend/Act"
			end
			if (@stat & 128 = 128)
			begin
				select @stat_to_print = "Act/Del"
				select @config_size = 0
			end

			/*
			**  Convert run_size and config_size to megabyte 
			**  values stored as strings
			*/
			select @run_sz_str =  rtrim(str(convert(float,@run_size)/1024,9,2))
				+ " Mb"
			select @config_sz_str = rtrim(str(convert(float,@config_size)/1024,9,2))
				+ " Mb"

			/*
			**  Extract the status and the type from the status
			**  field since  both bit values are stuffed into
			**  this one field.
			*/

			if (@stat & 2 = 2)
			begin
				select @cache_type = "Mixed"
			end
			if (@stat & 4 = 4)
			begin
				select @cache_type = "Log Only"
			end
			if (@stat & 1 = 1)
			begin
				select @cache_type = "Default"	
			end
		 
			/*
			**  Update totals for config and run size
			*/
			select @total_cfg_sz = @total_cfg_sz + 
					convert(float, @config_size)
			select @total_run_sz = @total_run_sz + 
					convert(float, @run_size)

			/*
			**  Now store the line of output for this cache
			*/
			insert #cache_info values 
				(@sysconf_name, @stat_to_print, @cache_type, 
				 @config_sz_str, @run_sz_str)
		end
		else
		begin
			/*
			** Row contains pool information. Select required
			** information.
			*/

			/* Determine pool size (in KB) */
			select @io_sz_str = substring(@io_sz_comment,1,
						charindex("K",@io_sz_comment)-1)

			/* Determine the availability of the pool */
			if ((@config_size = 0) and 
			    (@run_size > 0) and
			    (@io_sz_str != "2"))
			begin
				/*
				** Pools, other than the 2K pool, which have
				** a configured size of 0, but a run size 
				** greater than zero could not be fully 
				** removed. Such pools will have been marked 
				** as unavailable by the server.
				*/
				select @pool_status = "Unavailable/deleted"
				select @pools_available = 0
			end
			else if ((@run_size < 512) and
				 (@io_sz_str != "2"))
			begin
				/*
				** Pools, other than the 2K pool, which have
				** a run size less than 512K will have
				** been marked as unavailable by the
				** server, since they are too small
				** to be used.
				*/
				select @pool_status = "Unavailable/too small"
				select @pools_available = 0
			end
			else
			begin
				/* Pool is available */
				select @pool_status = ""
			end

			insert #pool_detail values 
				(@sysconf_name, 
				 replicate(" ", 6 -
					(charindex("K", @io_sz_comment))) +
					substring(@io_sz_comment,1,
				 	charindex("K",@io_sz_comment)-1) + 
					" Kb ",
				 str(@wash_size,6) + " Kb",
				 rtrim(str(convert(float,@config_size) / 
					1024, 9, 2)) + " Mb",
				 rtrim(str(convert(float,@run_size) / 
					1024, 9, 2)) + " Mb",
				 @pool_status)
		end
		select @row_count = @row_count - 1
	end

	/*
	** Print cache information
	*/
	select cache_name "Cache Name", Status, Type, 
		configval "Config Value", runval "Run Value"
	from #cache_info

	/*
	**  Now print totals.
	*/
	select @run_sz_str =  str(convert(float,@total_run_sz) / 1024, 7, 2) + 
					" Mb"
	select @config_sz_str = str(convert(float,@total_cfg_sz) / 1024, 7, 2) +
					" Mb"

	select @print_str = convert(char(51), " ") + "------------ ------------"
	print @print_str 
	select @print_str = convert(char(44), " ") + "Total    " + 
		convert(char(13), @config_sz_str) + @run_sz_str
	print @print_str

	/*
	** Now print cache/pool detail information 
	** A "Pend/Act" cache will not have pools configured
	*/

	select @mincachename = min(cache_name) 
		from #cache_info 
		where Status != "Pend/Act"
	while @mincachename is not null
	begin

	/* 
	** Print information about the cache
	*/

	print '=========================================================================='
	select @print_str = "Cache: " + @mincachename + ",   Status: " + Status + 
			",   Type: " + Type 
		from #cache_info
		where cache_name = @mincachename
	print @print_str
	select @print_str = "      Config Size: " + ltrim(configval) + 
		",   Run Size: " + ltrim(runval)
		from #cache_info
		where cache_name = @mincachename
	print @print_str

	/*
	** Now print the pool information. Only print status information
	** if any pool is unavailable. This will happen so seldom, that for
	** the most part it is better to leave the output as documented in 
	** the user manuals to prevent unwanted Tech Support calls about
	** the meaning of this status field. 
	*/
	if exists (select * from #pool_detail where cache_name = @mincachename)
	begin
		if (@pools_available = 1)
		begin
			select io_sz "IO Size", wash_size "Wash Size", 
				configval "Config Size", runval "Run Size" 
				from #pool_detail
				where cache_name = @mincachename 
		end
		else
		begin
			select io_sz "IO Size", wash_size "Wash Size", 
				configval "Config Size", runval "Run Size", 
				pool_status "Status"
				from #pool_detail
				where cache_name = @mincachename 
		end
	end
	select @mincachename = min(cache_name)
		from #cache_info 
		where cache_name > @mincachename 
			and Status != "Pend/Act"
		if @mincachename is null break
	end
end
else
begin
	/* 
	** check if user has sa role, proc_role will also do auditing
	** if required. proc_role will also print error message if required.
	*/
	if (proc_role("sa_role") = 0)
		return (1)

	/*
	**  We actually have some real work to do; either insert, modify, or
	**  delete a cache. Initialize configured size and new type.
	*/
	select @config_sz_str = NULL
	select @new_cache_type = 0
	select @dflt_ctype = 0
	select @print_reboot_msg = "yes"

	/*
	** Here the @parm1 can be either a cache type or cache size. 
	** First check whether this is a cache type.
	*/
	if @parm1 = "logonly" or @parm1 = "mixed"
	begin
		if @parm1 = "logonly"
			select @new_cache_type = 4
		else
			select @new_cache_type = 2
		select @print_reboot_msg = "no"
	end
	else
	begin
		/* 
		** Here @parm1 could contain a junk string value or a
		** legitimate cache size.
		*/

		if patindex("%[a-z,A-Z]%", @parm1) = 1
		begin
			/* 
			** @parm1 has a junk value.  Display en error 
			** message, a usage message, and exit.
			*/
			exec sp_getmessage 18155, @print_str output
			print @print_str 
			exec sp_getmessage 18177, @print_str output
			print @print_str 
			return(1)
		end
		else
		begin
			/* @parm1 has a cache size */
			select @config_sz_str = @parm1
		end	
	end

	/*
	**  See what's in parm2.
	*/
	if @parm2 = "logonly" or @parm2 = "mixed"
	begin
		/*
		**  It's a syntax error if the parm1 already had the cache
		**  type in it.
		*/
		if @new_cache_type != 0
		begin

			exec sp_getmessage 18136, @print_str output
			print @print_str 
			exec sp_getmessage 18177, @print_str output
			print @print_str 
			return(1)
		end	

		/*
		**  It's either log only or mixed.
		*/
		if @parm2 = "logonly"
			select @new_cache_type = 4
		else
			select @new_cache_type = 2
	end
	else 
	begin
		/*
		** If we reach here @parm2 could be either NULL or
		** have a junk string for the cache type.  If it 
		** has a NULL value and the cache type was not specified
		** in @parm1, then default the cache type to mixed.
		** We also indicate that the cache type was unspecified
		** by setting @dflt_ctype to 1. So that later, if we are
		** doing an update, we dont overwrite a logonly cache type
		** with the default mixed type.
		*/
		if @parm2 is NULL
		begin
			if @new_cache_type = 0
			begin
				select @new_cache_type = 2
				select @dflt_ctype = 1
			end
		end
		else
		begin
			/* 
			** @parm2 has a junk value.  Display an error
			** message and then exit.
			*/
			exec sp_getmessage 18155, @print_str output
			print @print_str 
			exec sp_getmessage 18177, @print_str output
			print @print_str 
			return(1)
		end
	end
	
	/*
	**  Find out if we need to update, insert, or delete this cache
	**  from sysconfigures.
	*/
	select @stat = -1

	select @stat = status from master.dbo.sysconfigures 
		   where parent = 19 and config = 19 and name = @cachename

	/* Convert the specified size into kbytes. */
	select @size = 0
	if @config_sz_str != NULL
	begin
		exec @ret = sp_aux_getsize @config_sz_str, @size output

		if @ret = 0
		begin
			exec sp_getmessage 18177, @print_str output
			print @print_str
			return(1)
		end
	end

	/*
	**  If the cache exists then it's an update or delete.
	*/
	if @stat != -1
	begin
		/* If the specified size is 0, then delete the cache. */
		if @config_sz_str != NULL AND  @size = 0
		begin
			if (@stat & 1 = 1)
			begin
				/*
				**  Can't delete the default cache.
				*/
				exec sp_getmessage 18137, @print_str output
				print @print_str
				return(1)
			end
			/*
			**  This is a cache delete.
			*/
			select @operation = 8
		end
		else
		begin
			/*
			**  This is a cache update.
			*/
			select @operation = 7
		end
		
	end
	else
	begin
		if (@config_sz_str = NULL or @size = 0)
		begin
			/* 
			**  Can't create a cache with 0 size
			*/
			exec sp_getmessage 18135, @print_str output
			print @print_str, @cachename
			return(1)
		end
			
		select @operation = 6
	end
		
	/*
	**  Begin a transaction.  We'll be modifying rows in sysconfigures
	**  and then calling the built-in function config_admin to verify the
	**  new configuration.  If config_admin fails the verification phase
	**  we'll have to rollback the changes to sysconfigures.
	*/
	begin tran cacheconfig

	if @operation = 6
	begin
		/*
		** This is a cache create.
		*/
		select @new_cache_type & 64
		insert into master.dbo.sysconfigures 
			values(19, @size, "User Defined Cache", 
				@new_cache_type | 64,
				@cachename, 19, @config_sz_str, 0)
	end
	else if @operation = 8
	begin
		/*
		**  This is a cache delete.
		**  Retain the existing cache type and set the Pend/Del (128)
		**  bit.
		*/
		update master.dbo.sysconfigures 
			set status = ((status & 7) | 128)
			where parent = 19 and name = @cachename
	end
	else if @operation = 7
	begin
		/*
		**  This is a cache update
		**  If @dflt_ctype is set to 1, we dont update the
		**  existing cache type with the default mixed type.
		*/
		if @new_cache_type != 0 and @dflt_ctype != 1
		begin
			/*
			**  If we're making the cache a log only cache then
			**  verify that there are no non-log objects bound to
			**  the cache.
			*/
			if (@new_cache_type & 4 = 4)
			begin
				select @stat = config_admin(9, 1, 0, 0, NULL,
							    @cachename)
				if @stat = 0
				begin
					exec sp_getmessage 18140, 
							   @print_str output
					print @print_str
					rollback tran cacheconfig
					return 1
				end
			end
					
			select @old_stat = status from master.dbo.sysconfigures 
				where config = 19 and parent = 19 and 
				name = @cachename

			/*
			**  If the cache type is changing then we need to
			**  turn off the old cache type bits in the status
			**  word before or-ing the new value in.
			*/
			if (@old_stat & @new_cache_type != @new_cache_type)
			begin
				select @old_stat = @old_stat & ~6
				select @old_stat = @old_stat | @new_cache_type 
				update master.dbo.sysconfigures 
					set status = @old_stat
				where parent = 19 and 
					name = @cachename
			end
			
		end

		if @config_sz_str != NULL
		begin
			update master.dbo.sysconfigures 
				set value2 = @config_sz_str, value = @size
			where config = 19 and parent = 19 and name = @cachename

			/*
			** Retain the current cache type and set status to
			** Active or Pend/Act if the current status is Pend/Del.
			*/
			select @stat = status from master.dbo.sysconfigures 
				where config = 19 and parent = 19 and 
				name = @cachename

			if (@stat & 128 = 128)
			begin
				if exists (select value from 
						master.dbo.syscurconfigs
						where config = 19 and
						 	comment = @cachename)
				begin
					/* 
					** The cache is active prior to 
					** being deleted. 
					*/
					select @stat = 32
				end
				else
				begin
					/* 
					** The cache is Pend/Act prior to
					** being deleted.
					*/
					select @stat = 64
				end

				Update master.dbo.sysconfigures
					set status = ((status & 7) | @stat)
					where parent = 19 and name = @cachename
			end
		end
	end

	select @stat = config_admin(@operation, 19, 0, @new_cache_type, 
							NULL, @cachename)
	if @stat = 0
	begin
		rollback tran cacheconfig
		return(1)
	end

	/*
	**  If the type of this cache has changed then we need to make sure
	**  that if the new type is log only, there are no non-log objects
	**  bound to this cache.
	*/
	if (@old_stat & @new_cache_type != @new_cache_type)
	begin
		if (@new_cache_type & 4 = 4)
		begin
			select @stat = 
				config_admin(9, 1, 0, 0, NULL, @cachename)
			if @stat = 0
			begin
				exec sp_getmessage 18140, @print_str output
				print @print_str
				rollback tran cacheconfig
				return(1)
			end
		end
	end

	commit tran cacheconfig

	if (@print_reboot_msg = "yes")
	begin
		exec sp_getmessage 18172, @print_str output
		print @print_str
	end

	return(0)
end	
go
exec sp_procxmode 'sp_cacheconfig', 'anymode'
go
grant execute on sp_cacheconfig to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_bindcache')
begin
	drop procedure sp_bindcache
end
go
print "Installing sp_bindcache"
go

/* Stored procedure for binding entites to named caches.  Entity must
** be the name of a database, table or index.
**
** Databases can only be bound when using Master.
** The Master database cannot be bound to a named cache, but individual
** tables in Master can.
*/

/*
** Messages for "sp_bindcache"	18086
**
**  17260, "Can't run %1! from within a transaction."
**  18086, "Specified named cache does not exist."
**  18087, "You must be in Master to bind or unbind a database."
**  18089, "The Master database cannot be bound to or unbound from
**	    a named cache."
**  18092, "Only logs may be bound to this cache."
**  18098, "Individual tables in TEMPDB cannot be bound to or unbound
**	    from named caches.  However, all of TEMPDB may be bound or
**	    unbound."
**  18156, "Usage: sp_unbindcache dbname [, [ownername.]tablename
**	    [, indexname | `text only']]"
**  18170, "Usage: sp_bindcache cachename, dbname [, [ownername.]tablename
**	    [, indexname | `text only']]"
**  18175, "Specified named cache does not exist. The SQL Server must be
**	    rebooted to activate the named cahce."
*/

create procedure sp_bindcache
@cachename	varchar(30),
@dbname		varchar(30),
@tablename	varchar(62) = NULL,
@indexname	varchar(30)  = NULL
as

declare @dbid		int
declare @ownerid	int
declare @objid		int
declare @indid		int
declare @entitytype	char(1)
declare @aiobject	int
declare @status		int
declare @separator	int
declare @mask		int
declare @cachecount	int
declare @class		smallint
declare @attribute	smallint
declare @action		smallint
declare @objtype	char(1)
declare @sysattrtype	char(2)
declare @msg 		varchar(255)


/*
**  Don't allow this in a transaction because we can't undo what
**  the bind_cache() builtin has done.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_bindcache"
	return (1)
end
else
begin
	set transaction isolation level 1
	set chained off
end

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/
if (proc_role("sa_role") = 0)
	return (1)

/* Make sure the target cache exists. */
if (@cachename != NULL)
begin
	select @status=0
	select @status = status from master.dbo.sysconfigures
		where name=@cachename and parent=19 and config=19
	/* if the named cache does not exist */
	if (@status = 0)
	begin
		exec sp_getmessage 18086, @msg output
		print @msg
		return 1
	end
	/* if the named cache is not active */
	if (@status & 32) != 32
	begin
		exec sp_getmessage 18175, @msg output
		print @msg
		return 1
	end
end

if @dbname is NULL
begin
	/*
	** Dbname is required for both sp_bindcache and sp_unbindcache.
	*/
	if @cachename = NULL
	begin
		/*
		** Raise the sp_unbindcache usage message.
		*/
		exec sp_getmessage 18156, @msg output
		print @msg
		return 1
	end
	else
	begin
		/*
		** Raise the sp_bindcache usage message.
		*/
		exec sp_getmessage 18170, @msg output
		print @msg
		return 1
	end
end

/*
** Retrieve the id's required to identify the object the cache is being
** bound to.
*/
select @status		= 0
select @dbid		= NULL
select @ownerid		= NULL
select @objid		= NULL
select @indid		= NULL
select @entitytype	= NULL
exec @status = sp_aux_parse_entity @dbname, @tablename, @indexname,
				   @dbid output, @ownerid output,
				   @objid output, @indid output,
				   @entitytype output

if @status = 2
begin
	/*
	** A syntax error was encountered.  Raise the appropriate usage
	** message.
	*/
	if @cachename = NULL
	begin
		/*
		** Raise the sp_unbindcache usage message.
		*/
		exec sp_getmessage 18156, @msg output
		print @msg
		return 1
	end
	else
	begin
		/*
		** Raise the sp_bindcache usage message.
		*/
		exec sp_getmessage 18170, @msg output
		print @msg
		return 1
	end
end
else if @status != 0
begin
	return @status
end

/*
** If we are [un]binding a database...
*/
if @entitytype = 'D'
begin
	/* 
	** Make sure we are currently in the master database.
	** If not display an error message and exit.
	*/
	if db_id() != 1
	begin
		exec sp_getmessage 18087, @msg output
		print @msg
		return 1
	end
	/* 
	** If the cache type is "logonly", make sure we are binding only
	** syslogs to it.  Binding a database to a "logonly" cache is illegal.
	*/
	select @status=0
	select @status = status from master.dbo.sysconfigures
		where name=@cachename and parent=19 and config=19
	select @mask = @status & 4
	if @mask > 0
	begin
		exec sp_getmessage 18092, @msg output
		print @msg
		return 1
	end

	/* Master itself cannot be bound */
	if @dbid = 1
	begin
		exec sp_getmessage 18089, @msg output
		print @msg
		return 1
	end

	select @aiobject = @dbid
end
else
begin
	/* Individual tables in tempdb cannot be bound. */
	if @dbid = 2
	begin
		exec sp_getmessage 18098, @msg output
		print @msg
		return 1
	end

	select @aiobject = @objid

	/* if the log-only bit is set, make sure we're binding the log. */
	select @status=0
	select @status = status from master.dbo.sysconfigures
		where name=@cachename and parent=19 and config=19
	select @mask = @status & 4
	if @mask > 0
	begin
		if (@objid != 8)
		begin
			exec sp_getmessage 18092, @msg output
			print @msg
			return 1
		end
	end
end

/*
** Map entity type to attribute type.  Note that the attribute manager
** needs a two-byte string...
*/
select @sysattrtype = @entitytype + " "

/* Figure out if we need to insert, update or delete from sysattributes. */
begin tran bindcache
if @cachename is not NULL
BEGIN
	if exists(select * from sysattributes where
		class = 3 AND
		attribute = 0 AND
		object_type = @sysattrtype AND
		object = @aiobject AND
		object_info1 = @indid)
	BEGIN
		select @action = 2 /* ATTR_CHANGE */
	END
	ELSE
	BEGIN
		select @action = 1 /* ATTR_ADD */
	END
END
ELSE
BEGIN
	select @action = 3 /* ATTR_DROP */
END

/*
**  Call the notification routine before modifying sysattributes.  This
**  is necessary because cm_bind_cache() needs to look up the OLD binding
**  for the entity.
*/
select @status = 0
select @class = 3
select @attribute = 0
select @status = attrib_notify(@class, @attribute, @sysattrtype, @aiobject,
			@indid, NULL, NULL, NULL, NULL, @cachename, NULL, 
			NULL, NULL, @action)

if @status = 1
BEGIN
	rollback tran bindcache
	return @status
END

if @action = 1
BEGIN
	insert into sysattributes 
		(class, attribute, object_type, object, 
		 object_info1, char_value, int_value)
		VALUES
		(3,	/* BUFFER MANAGER */
		 0,	/* CACHE BINDING */
		 @sysattrtype,
		 @aiobject,
		 @indid,
		 @cachename,
		 1	/* Binding is valid */
		)
END

if @action = 2
BEGIN
	update sysattributes
		set 	char_value = @cachename,
			int_value = 1	/* binding is valid */
		where	class = 3 AND
			attribute = 0 AND
			object_type = @sysattrtype AND
			object = @aiobject AND
			object_info1 = @indid
END

if @action = 3
BEGIN
	delete from sysattributes
			where	class = 3 AND
				attribute = 0 AND
				object_type = @sysattrtype AND
				object = @aiobject AND
				object_info1 = @indid
END

commit tran bindcache	

return @status
go
exec sp_procxmode 'sp_bindcache', 'anymode'
go
grant execute on sp_bindcache to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_poolconfig')
begin
	drop procedure sp_poolconfig
end
go
print "Installing sp_poolconfig"
go

/* This stored procedure is for configuring buffer pools.
**
**	Messages for sp_poolconfig
**
** 17260, "Can't run %1 from within a transaction."
**
** 18095, "The destination buffer pool size must be a minimum of 512 kilobytes."
**
** 18138, "A cache name must be supplied."
**
** 18135, "The specified named cache (%1) does not exist."
**
** 18141, "Syntax error encountered. Specification of the wash size must be 
**	   of the form 'wash = %d[PKMG]'
**
** 18142, "I/O size of the memory pool is expected as the third argument."
**
** 18143, "The source pool (%1k buffers, total size %2k) is not large enough 
**	   to satisfy the request to move %3k of memory.
**
** 18144, "Source pool (%1k) and destination pool (%2k) are the same pool.  
**	   The source and destination pools must be different."
**
** 18147, "Invalid buffer size of %1! encountered. Valid buffer sizes are 
**	   powers of two between 2k and 16k inclusive."
**
** 18148, "The specified pool (%1!) does not exist in named cache '%2!'."
**
** 18339, "Could not find at least 512k space for the buffer pool '%1!'.
**         Make sure the cache '%2!' is not in use when running 
**         sp_poolconfig."
**
** 18558, "Unable to delete the '%1!' pool in cache '%2!'."
**
** 18559, "This pool has been marked unavailable. You can
**	   remove it completely by retrying sp_poolconfig when
**	   the cache is not in use or by restarting the Server."
** 
** 18560, "Unable to move '%1!' from the '%2!' pool to the '%3!' pool in
**	   cache '%4!'. Only '%5!' moved."
** 
** 18561, "The '%1!' pool has been marked as being unavailable since it is
**	   smaller than the minimum pool size of 512KB."
** 
** 18562, "You can size the pools correctly by retrying sp_poolconfig 
**	   when the cache is not in use or by restarting the Server."
*/

create procedure sp_poolconfig
@cachename 	varchar(30) = NULL,
@parm1		varchar(30) = NULL,
@parm2		varchar(30) = NULL,
@parm3		varchar(30) = NULL
as

declare @equal_sign_loc		int	/* for parsing parms */
declare @wash_val_loc		int	/* for parsing parms */
declare @wash_size		int	/* user supplied wash size */
declare @wash_delta_size	int	/* delta of the wash size */
declare	@src_buf_size		int	/* size of bufs in src pool */
declare @dest_buf_size		int	/* size of bufs in dest pool */
declare @config_num_src		int	/* config # for src pool */
declare @config_num_dest	int	/* config # for dest pool */
declare	@temp_size		int	/* temporary variable */
declare @requested_size		int	/* requested total size of dest pool */
declare @existing_pool_size	int	/* exisiting size of dest pool */
declare @stat			int	/* status of cache from sysconfigures */
declare @mem_to_move		int	/* amount of mem to move */
declare @mem_moved		int	/* Memory that should have been moved */
declare @src_pool_size		int	/* amount of mem in src pool */
declare @dest_pool_size		int	/* amount of mem in dest pool */
declare	@ret			int	/* return status from sp_aux_getsize */
declare	@result_size		int	/* resulting size of dest pool after
					** config_admin call
					*/
declare @delete_pool		int	/* 1 if src pool 2 if dest pool */
declare @temp_float		float	/* for temp float calculations */
declare @temp_value		int	/* for temp int calculations */
declare @temp_pool_size		int	/* for temp pool size value */
declare	@dest_buf_sz_str	varchar(30) /* size of bufs in dest pool */
declare	@src_buf_sz_str		varchar(30) /* size of bufs in src pool */
declare	@dest_pool_sz_str	varchar(30) /* total mem in dest pool */
declare @res_sz_str		varchar(30) /* str value of result size */
declare @req_sz_str		varchar(30) /* str value of requested size */
declare @temp_str		varchar(30) /* scratch pad */
declare @wash_str		varchar(255) /* wash size */
declare @msg			varchar(255)
declare	@config_file_name	varchar(255)

select @wash_str = NULL

if @@trancount > 0
begin
	/* 17260, "Can't run %1 from within a transaction." */
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_poolconfig"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

if @cachename = NULL
begin
	/*
	**  Must supply a cache name.
	*/
	exec sp_getmessage 18138, @msg output
	print @msg
	return 1
end

/*
**  If the cache name is the only parameter that's supplied just pass it 
**  along to sp_cacheconfig and have it print out all of the configured pools
**  for the cache.
*/
if (@parm1 = NULL) and (@parm2 = NULL) and (@parm3 = NULL) 
begin
	exec sp_cacheconfig @cachename
	return 0
end

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/
if (proc_role("sa_role") = 0)
	return (1)

/*
**  Check to see if the cache exists
*/
select @stat = -1
select @stat = status from master.dbo.sysconfigures where name=@cachename and 
			status & 128 != 128
if @stat = -1
begin
	exec sp_getmessage 18135, @msg output
	print @msg, @cachename
	return 1
end

select @dest_pool_sz_str = @parm1

/*
**  Parm2 may be of the form "wash = %d" or %d [K | M | G]
*/
if patindex("%wash%", @parm2) != 0
begin
	/*
	**  Translate destination buffer pool into units of k
	*/
	exec  @ret = sp_aux_getsize @dest_pool_sz_str, @dest_buf_size output

	if @ret = 0
		return 1

	select @equal_sign_loc = 0
	select @equal_sign_loc = patindex("%=%", @parm2)
	/*
	**  proper syntax for specifying the wash is "wash = %d". Make sure 
	**  the string follows this syntax.
	*/
	if @equal_sign_loc = 0
	begin
		exec sp_getmessage 18141, @msg output
		print @msg
		return 1
	end

	select @wash_val_loc = patindex("%[0-9]%", @parm2)
	select @wash_str = convert(varchar(255), substring(@parm2, 
				 	@wash_val_loc, 
				 	char_length(@parm2) - 
						@wash_val_loc + 1))

	/*
	**  sp_aux_get_size will take string of the form "100 [kmpg]"
	**  
	*/
	exec @ret = sp_aux_getsize @wash_str, @wash_size output
	if @ret = 0
		return 1

	/*
	**  First sanity check the destination buffer size to make sure it's 
	**  within the legal range (i.e. powers of 2 between 2k and 16k.
	*/
	if @dest_buf_size < (@@pagesize / 1024) or @dest_buf_size > (8 * @@pagesize / 1024)
	begin
		exec sp_getmessage 18147, @msg output
		print @msg, @dest_pool_sz_str
		return 1
	end

	/*
	**  Check to see if the destination buffer size is a power of two.
	*/
	select @temp_size = 2
	while @temp_size < @dest_buf_size
		select @temp_size = @temp_size * 2
	if @temp_size != @dest_buf_size
	begin
		exec sp_getmessage 18147, @msg output
		print @msg, @dest_pool_sz_str
		return 1
	end
	
	/*
	**  Config numbers in sysconfigures start at 20 for the 2k buffer pool,
	**  21 for the 4k buffer pool, 22 for the 8k buffer pool and so on.
	**  Basically if we add log base 2 of the destination buffer size to
	**  the base of 20 and subtract one we should get the correct config 
	**  number to index into sysconfigures.
	*/
	select @config_num_dest = 20 + (log10(@dest_buf_size * 1024 / @@pagesize) / log10(2))

	/*
	**  Figure out how many buffers to add or subtract from the wash.
	*/
	select @temp_size = memory_used from master.dbo.syscurconfigs where 
		config = @config_num_dest and comment = @cachename

	/*
	**  If the pool doesn't exist it's an error.  Can't modify the wash
	**  size for a non-existent pool.
	*/
	if @temp_size = 0
	begin
		exec sp_getmessage 18148, @msg output
		print @msg, @dest_pool_sz_str, @cachename
		return 1
	end

	select @wash_delta_size = @wash_size - @temp_size

	/*
	** In syscurconfigs, we obtain the wash size in Kilobytes.
	** However, we store the wash size, in sysconfigures, in
	** kilobytes/Buffer pool size.
	** Note: we are reusing the variable 'temp_size' here.
	*/
	select @temp_size = @wash_size / @dest_buf_size

	/*
	** If due to round off error, we get a wash_size of 0, even if
	** it was not specified as the input, we will pass a non-zero
	** invalid value to the update. This will be caught by the config
	** manager and this update will rolled back later. This can happen, 
	** if the wash size specified is not zero, but gets rounded of to 
	** zero. The wash size 0 is a special value.
	*/
	if @temp_size = 0 and @wash_size != 0
		select @temp_size = -1

	begin tran set_wash

	update master.dbo.sysconfigures
		 set value3 = @temp_size
		 where config = @config_num_dest and name = @cachename
		
	select @stat = config_admin(10, @dest_buf_size, @wash_delta_size, 0,
				    NULL, @cachename)

	if @stat = 0
	begin
		rollback tran set_wash
		return 1
	end

	commit tran set_wash
	return 0
end

/*
**  If we make it here then the command must be of the form:
**		sp_poolconfig "foo", "100M", "16k"
**  We'll check against that syntax here.
*/
if @parm2 = NULL
begin
	exec sp_getmessage 18142, @msg output
	print @msg
	return 1
end

select @dest_buf_sz_str = @parm2

if @parm3 = NULL
begin
	select @src_buf_sz_str = "1p"
end
else
begin
	select @src_buf_sz_str = @parm3
end

/*
**  Convert the destination pool size to units of kilobytes.
*/
exec  @ret = sp_aux_getsize @dest_pool_sz_str, @requested_size output
if @ret = 0
	return 1 

/*
**  First sanity check the destination pool size to make sure
**  it is atleast 512k.
*/
if (@requested_size != 0 and  @requested_size < 512)
begin
	exec sp_getmessage 18095, @msg output
	print @msg, @dest_pool_sz_str
	return 1
end

/*
**  Translate the size in K of the destination and src pools to a 
**  config value that we can use to look up the pool in sysconfigures.
*/
exec  @ret = sp_aux_getsize @dest_buf_sz_str, @dest_buf_size output
if @ret = 0
	return 1
exec @ret = sp_aux_getsize @src_buf_sz_str, @src_buf_size output
if @ret = 0
	return 1

/* 
**  The source and destination pools cannot be the same.
*/
if @dest_buf_size = @src_buf_size
begin
	exec sp_getmessage 18144, @msg output
	print @msg, @src_buf_sz_str, @dest_buf_sz_str
	return 1
end

/*
**  Sanity check the destination and source buffer sizes to make sure it's 
**  within the legal range (i.e. powers of 2 between 2k and 16k.
*/
if (@dest_buf_size < (@@pagesize / 1024) or @dest_buf_size > (8 * @@pagesize / 1024))
begin
	exec sp_getmessage 18147, @msg output
	print @msg, @dest_buf_sz_str
	return 1
end

if (@src_buf_size < (@@pagesize / 1024) or @src_buf_size > (8 * @@pagesize / 1024))
begin
	exec sp_getmessage 18147, @msg output
	print @msg, @src_buf_sz_str
	return 1
end

/*
**  Check to see if the destination buffer size is a power of two.
*/
select @temp_size = 2
while @temp_size < @dest_buf_size
	select @temp_size = @temp_size * 2
if @temp_size != @dest_buf_size
begin
	exec sp_getmessage 18147, @msg output
	print @msg, @dest_buf_sz_str
	return 1
end

/*
**  Check to see if the source buffer size is a power of two.
*/
select @temp_size = 2
while @temp_size < @src_buf_size
	select @temp_size = @temp_size * 2
if @temp_size != @src_buf_size
begin
	exec sp_getmessage 18147, @msg output
	print @msg, @src_buf_sz_str
	return 1
end

/*
**  Translate buffer sizes into config numbers to index into sysconfigures
**  and syscurconfigs with.
*/
select @config_num_src = 20 + (log10(@src_buf_size * 1024 / @@pagesize) / log10(2))
select @config_num_dest = 20 + (log10(@dest_buf_size * 1024 / @@pagesize) / log10(2))

/*
**  Find out how much memory is already in the destination pool.  It could
**  turn out that this request is for making the pool smaller.  In that case
**  turn around the arguments (i.e. destination pool becomes source and source
**  pool becomes destination) and give the extra memory to the source
**  pool.
*/

select @delete_pool = 0
select @existing_pool_size = 0
select @existing_pool_size = value from master.dbo.syscurconfigs where
	comment=@cachename and config = @config_num_dest

select @mem_to_move = @requested_size - @existing_pool_size

/*
**  If there is nothing to move just return. No need to work 
**  without a good reason.
*/

if @mem_to_move = 0
begin
	return 0
end

begin tran pool_config

/*
**  If the memory to move is positive, we're moving memory from the source
**  pool (parm3) to the destination pool (parm2).  If it is negative then
**  we're moving memory from the destination pool (parm2) to the source
**  pool (parm3). Negative memory indicates that we're making a pool smaller.
*/
if @mem_to_move > 0
begin
	/*
	**  Check to see if the source pool has enough memory in it to
	**  satisfy the request.
	*/
	select @src_pool_size = 0
	select @src_pool_size = value from master.dbo.syscurconfigs
		where config=@config_num_src and 
		comment = @cachename
	select @temp_size = @src_pool_size - @mem_to_move
	if (@temp_size != 0 and @temp_size < 512)
	begin
		/*
		** Use wash_str to covert mem_to_move to string
		*/
		select @wash_str = rtrim(convert(varchar(20), @mem_to_move)) + "Kb"
		exec sp_getmessage 18143, @msg output
		print @msg, @src_buf_sz_str, @src_pool_size,
			    @wash_str 

		/*
		** We are not using a rollback tran here as it will
		** complain that their is nothing to rollback. The
		** reason being we have not done any work in this
		** transaction so far.
		*/
		commit tran poolconfig
		return 1
	end
	
	if exists (select * from master.dbo.sysconfigures where
		name=@cachename and config = @config_num_dest)
	begin
		/*
		** @temp_str contains the string equivalent of @requested_size
		** in @dest_pool_sz_str format.
		*/
		exec sp_aux_getsize @dest_pool_sz_str, @temp_pool_size output,
				@requested_size, @temp_str output 
		
		update master.dbo.sysconfigures 
			set 	value = @requested_size,
			    	value2 = @temp_str
			where 	config = @config_num_dest and
				name = @cachename
		
	end
	else
 	begin
		select @stat = status from master.dbo.sysconfigures
			where name = @cachename and config=19

		select @msg = rtrim(convert(varchar(255), @dest_buf_size)) +
				"K I/O Buffer Pool"

		exec sp_aux_getsize @dest_pool_sz_str, @temp_pool_size 
			output, @requested_size, @temp_str output 

		/*
		** Note the last value for the insert below is '0'. This
		** corresponds to the wash size of the newly created buffer
		** pool. Newly created pools get a wash size of zero which 
		** corresponds to default wash size.
		*/
		insert into master.dbo.sysconfigures values (@config_num_dest,
						  @requested_size,
						  @msg,
						  @stat,
						  @cachename,
						  19,
						  @temp_str,
						  0)
	end
	
	if @temp_size = 0
	begin
		/* Flag that we should delete the source buffer pool later. */
		select @delete_pool = 1
	end
		
	/* 
	** Update the source pool size after transfer.
	** If the updated value would become negative then
	** set it to zero.  @temp_str contains the string equivalent 
	** of the value field in @src_pool_sz_str format.
	*/
	select @temp_size = value - @mem_to_move from master.dbo.sysconfigures
		where config = @config_num_src and
			name = @cachename
	if @temp_size < 0
	begin	
		exec sp_aux_getsize @dest_pool_sz_str, @temp_pool_size 
			output, 0, @temp_str output 
		update master.dbo.sysconfigures 
			set 	value = 0,
				value2 = @temp_str
			where 	config = @config_num_src and
				name = @cachename 
	end
	else
	begin
		exec sp_aux_getsize @dest_pool_sz_str, @temp_pool_size 
			output, @temp_size, @temp_str output 
		update master.dbo.sysconfigures 
			set 	value = @temp_size,
				value2 = @temp_str	
			where 	config = @config_num_src and
				name = @cachename 
	end
end
else
begin
	/*
	**  We're actually removing memory from the destination pool since
	**  @mem_to_move is negative.  If we've deleted this pool then delete
	**  the entry from sysconfigures.  Otherwise just subtract (by adding
	**  -@mem_to_move from the value already in sysconfigures).
	*/
	/* Check to see whether we have enough space in the dest pool */
	select @dest_pool_size = 0
	select @dest_pool_size = value from master.dbo.syscurconfigs
		where config=@config_num_dest and 
		comment = @cachename
	select @temp_size = @dest_pool_size + @mem_to_move
	if (@temp_size != 0 and @temp_size < 512)
	begin
		/*
		** Use wash_str to covert mem_to_move to string
		*/
		select @wash_str = rtrim(convert(varchar(20), @mem_to_move)) + "Kb"
		exec sp_getmessage 18143, @msg output
		print @msg, @dest_buf_sz_str, @dest_pool_size,
			    @wash_str 

		/*
		** We are not using a rollback tran here as it will
		** complain that their is nothing to rollback. The
		** reason being we have not done any work in this
		** transaction so far.
		*/
		commit tran poolconfig
		return 1
	end
	
	if exists (select * from master.dbo.sysconfigures where
		name=@cachename and config = @config_num_src)
	begin
		
		/*
		** @temp_str contains the string equivalent of value field 
		** in @src_pool_sz_str format.
		*/
		select @temp_value = value + abs(@mem_to_move) 
		from master.dbo.sysconfigures
			where 	config = @config_num_src and
				name = @cachename	
		exec sp_aux_getsize @dest_pool_sz_str, @temp_pool_size output,
			@temp_value, @temp_str output 
		update master.dbo.sysconfigures 
			set 	value = @temp_value,
				value2 = @temp_str
			where 	config = @config_num_src and
				name = @cachename
		
	end
	else
 	begin
		select @stat = status from master.dbo.sysconfigures
			where name = @cachename and config=19

		select @msg = rtrim(convert(varchar(255), @src_buf_size)) +
				"K I/O Buffer Pool"
		select @temp_value = abs(@mem_to_move)
		exec sp_aux_getsize @dest_pool_sz_str, @temp_pool_size output,
			@temp_value, @temp_str output 
		/*
		** Note the last value for the insert below is '0'. This
		** corresponds to the wash size of the newly created buffer
		** pool. Newly created pools get a wash size of zero which 
		** corresponds to default wash size.
		*/
		insert into master.dbo.sysconfigures values (@config_num_src,
						  @temp_value,
						  @msg,
						  @stat,
						  @cachename,
						  19,
						  @temp_str,
						  0)
	end
	
	if @temp_size = 0
	begin
		/* 
		** Flag that we should delete the destination buffer pool 
		** later. 
		*/
		select @delete_pool = 2
	end

	/* 
	** Update the destination pool size after transfer.
	** @temp_str contains the string equivalent
	** of the value field @dest_pool_sz_str format.
	*/
	exec sp_aux_getsize @dest_pool_sz_str, @temp_pool_size 
		output, @requested_size, @temp_str output 
	update master.dbo.sysconfigures 
		set 	value = @requested_size, 
			value2 = @temp_str 
		where 	config = @config_num_dest and 
			name = @cachename 

end

select @stat = config_admin(11, @src_buf_size, @mem_to_move, @dest_buf_size,
				NULL, @cachename)
if @stat = 0
begin
	rollback tran pool_config
	return 1
end

select @result_size = value from master.dbo.syscurconfigs 
	where config=@config_num_dest and 
	comment = @cachename

/*
** SQL Server cannot guarentee that all of the requested buffers can be
** moved from one pool to another. Determine if the correct number of 
** buffers were moved.
**
** When moving memory, SQL Server cannot move fractions of MASSes. Therefore
** the actual amount of memory moved may be rounded down to a multiple
** of the greater of the source and destination MASS size. Take this
** into account when determining if the request has been fulfilled.
** For example, if a request is made to move 28K from the 2K to the 8K
** pool, then the server will only attempt to move 24K, since half a
** MASS (the remaining 4K) has no meaning to the 8K pool.
**
** NOTE: This fact creates a dependency between the server's behaviour and
** the behaviour of sp_poolconfig, and care should be taken in future not
** to break this. These sorts of dependencies will continue to exist until
** such time as config_admin() is modified to return good status 
** information. The stored procedure needs to know whether the memory move
** succeeded or not, and should not be left to duplicate the server's 
** behaviour in order to work this out.
** 
** Calculate this rounded down value and save it in @mem_moved.
*/
if @src_buf_size > @dest_buf_size
begin
        select @temp_value = @mem_to_move / @src_buf_size
        select @mem_moved = @temp_value * @src_buf_size
end
else
begin
        select @temp_value = @mem_to_move / @dest_buf_size
        select @mem_moved = @temp_value * @dest_buf_size
end

/*
** If the requisite number of buffers were moved successfully between 
** pools, remove corresponding entries from sysconfigures if this was a 
** request to delete a pool.
*/
if @result_size = (@mem_moved + @existing_pool_size)
begin
	if @delete_pool = 1
	begin
		delete from master.dbo.sysconfigures
			where config = @config_num_src and 
			      name   = @cachename
		select @stat = config_admin(9, 5, @src_buf_size * 1024, 0, NULL, @cachename)
	end
	if @delete_pool = 2
	begin
		delete from master.dbo.sysconfigures
			where config = @config_num_dest and
			      name   = @cachename
		select @stat = config_admin(9, 5, @dest_buf_size * 1024, 0, NULL, @cachename)
	end
end
else
begin
	/*
	** Unable to move the requested number of buffers. If this was an
	** attempt to delete a pool then generate a message indicating
	** the failure to fully do do. The pool will have been marked
	** as unavailable by the server in such cases.
	*/
	if (@delete_pool > 0)
	begin
		exec sp_getmessage 18558, @msg output

		if (@delete_pool = 1)
		begin
			/* Attempt to delete source pool */
			print @msg, @src_buf_sz_str, @cachename
		end
		else
		begin
			/* Attempt to delete destination pool */
			print @msg, @dest_buf_sz_str, @cachename
		end

		exec sp_getmessage 18559, @msg output
		print @msg
	end
	else
	begin
		/*
		** Unable to move the correct number of buffers, but there
		** was no attempt to delete either source or destination
		** pool.
		*/
		select @res_sz_str = 
			rtrim(convert(varchar(30), 
				abs(@existing_pool_size - @result_size)))
		select @req_sz_str = rtrim(convert(varchar(30), 
						abs(@mem_to_move)))
		exec sp_getmessage 18560, @msg output

		if (@mem_to_move > 0)
		begin
			/* Attempting to move from source to destination */
			print @msg, @req_sz_str, @src_buf_sz_str, 
				@dest_buf_sz_str, @cachename, @res_sz_str
		end
		else
		begin
			/* Attempting to move from destination to source */
			print @msg, @req_sz_str, @dest_buf_sz_str, 
				@src_buf_sz_str, @cachename, @res_sz_str
		end

		/*
		** If the destination pool has been left with a size of
		** less than 512K, then the server will have marked this
		** pool as unuseable. Print a warning in such cases.
		*/
		if (@result_size != 0 and @result_size < 512)
		begin
			exec sp_getmessage 18561, @msg output
			print @msg, @dest_buf_sz_str 
		end

		/*
		** If the source pool has been left with a size of
		** less than 512K, then the server will have marked this
		** pool as unuseable. Print a warning in such cases.
		*/
		select  @result_size = value from master.dbo.syscurconfigs
			where config=@config_num_src and 
			comment = @cachename

		if (@result_size != 0 and @result_size < 512)
		begin
			exec sp_getmessage 18561, @msg output
			print @msg, @src_buf_sz_str 
		end

		/*
		** Print a general message as to how to correctly resize
		** the pools.
		*/
		exec sp_getmessage 18562, @msg output
		print @msg
	end
end

/*
** Update the wash size for source and destination buffer pools if required.
** We do this at the end because, here the actual buffer movement
** has already been done and we will have the new wash size available
** for the affected buffer pools.
**
** NOTE: In syscurconfigs, we obtain the wash size in Kilobytes.
** However, we store the wash size, in sysconfigures, in
** kilobytes/Buffer pool size.
*/

/*
** Update wash size for the source buffer pool
*/

/*
** There are two system tables which has all the config information.
** syscurconfigs maintains current running configuration and sysconfigures
** contains the configuration user has asked through config file and
** using config releated commands. The values in these two system catalogs
** may be different because server might calculate some values for example
** if wash size is DEFAULT (i.e value3=0 in sysconfigures) server will find
** out what is the optimal wash size and set that in syscurconfigs where as
** sysconfigures will have 0 only. This is useful because when memory is
** moved between pools and if user give wash size as DEFAULT server adjusts
** to optimal value otherwise wash size might become more than the pool
** hence memory may not be allowed to move. 
*/

/*
** Get the current wash size from sysconfigures.
*/
select @temp_value = value3 from master.dbo.sysconfigures 
	where config = @config_num_src and name = @cachename
/*
** At this point user has created or modified a pool. We should not update the
** wash size here because it was not specified as a parameter.
** We should leave wash size as 0 which indicates a default value.
** @temp_value will not be zero if user has explicitly changed the wash size 
** at some point of the time, in such cases we should go update the
** value to that of running value because server might give a diffrent wash
** size than we asked for.
*/

if (@temp_value != 0)
begin
	select @wash_size = memory_used from master.dbo.syscurconfigs where 
		config = @config_num_src and comment = @cachename

	update master.dbo.sysconfigures 
		set value3 = @wash_size / @src_buf_size
		where config = @config_num_src and 
		      name = @cachename
end

/*
** Get the current wash size from sysconfigures.
*/
select @temp_value = value3 from master.dbo.sysconfigures 
	where config = @config_num_dest and name = @cachename
/*
** At this point user has created or modified a pool. We should not update the
** wash size here because it was not specified as a parameter.
** We should leave wash size as 0 which indicates a default value.
** @temp_value will not be zero if user has explicitly changed the wash size 
** at some point of the time, in such cases we should go update the
** value to that of running value because server might give a diffrent wash
** size than we asked for.
*/

if (@temp_value != 0)
begin
	select @wash_size = memory_used from master.dbo.syscurconfigs where 
	config = @config_num_dest and comment = @cachename

	update master.dbo.sysconfigures 
		set value3 = @wash_size / @dest_buf_size
		where config = @config_num_dest and 
		      name = @cachename
end

select @config_file_name = value2 from master.dbo.syscurconfigs
				  where config = 114
	
select @stat = config_admin(5, 0, 0, 0, NULL, @config_file_name)

if @stat = 0
begin
	rollback tran pool_config
	return 1
end

commit tran pool_config

return 0
go
exec sp_procxmode 'sp_poolconfig', 'anymode'
go
grant execute on sp_poolconfig to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindcache')
begin
	drop procedure sp_unbindcache
end
go
print "Installing sp_unbindcache"
go

/* Stored procedure for unbinding entites that are bound to named caches.
**
** Databases can only be unbound when using Master.
*/
create procedure sp_unbindcache
@dbname		varchar(30),
@tablename	varchar(62) = NULL,
@indexname	varchar(30) = NULL
as

declare @returncode 	smallint
declare @msg		varchar(250)

/*
**  Don't allow this in a transaction because we can't undo what
**  the bind_cache() builtin has done.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "bindcache"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/
if (proc_role("sa_role") = 0)
	return (1)

execute @returncode = sp_bindcache NULL, @dbname, @tablename, @indexname

return @returncode
go
exec sp_procxmode 'sp_unbindcache', 'anymode'
go
grant execute on sp_unbindcache to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_unbindcache_all')
begin
	drop procedure sp_unbindcache_all
end
go
print "Installing sp_unbindcache_all"
go

/* Stored procedure for unbinding all entites bound to a named cache.
**
**    Databases can only be unbound when using Master.
**
**	Messages for sp_cacheconfig
**
** 17260, "Can't run %1 from within a transaction."
**
** 18135, "The specified named cache (%1) does not exist"
** 
*/
create procedure sp_unbindcache_all
@cachename	varchar(30)
as

declare @msg		varchar(250)
declare @status		integer

/*
**  Don't allow this in a transaction because we can't undo what
**  the bind_cache() builtin has done.
*/
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @msg output
	print @msg, "bindcache"
	return (1)
end
else
begin
	set chained off
end

set transaction isolation level 1

/* check if user has sa role, proc_role will also do auditing
** if required. proc_role will also print error message if required.
*/
if (proc_role("sa_role") = 0)
	return (1)

if not exists (select * from master.dbo.sysconfigures where name = @cachename
		and config = 19)
begin
	exec sp_getmessage 18135, @msg output
	print @msg, @cachename
	return(1)
end

select @status = config_admin(9, 3, 0, 0, NULL, @cachename)

/*
**  The builtin returns TRUE for success, FALSE for failure.
**  Translate that into the stored procedure lingo where 0 is success.
*/
if (@status = 1)
begin
	return(0)
end
else
begin
	return (1)
end

go
exec sp_procxmode 'sp_unbindcache_all', 'anymode'
go
grant execute on sp_unbindcache_all to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setrepcol')
begin
	drop procedure sp_setrepcol
end
go
print "Installing sp_setrepcol"
go

/* Sccsid = "@(#) generic/sproc/setreplicate 155.1 11/10/94" */
/*
** Messages for "sp_setreplicate"	17960
**
** 17230, "Only the System Administrator (SA) or the Database Owner
**	   (dbo) may execute this stored procedure."
** 17460, "Object must be in the current database."
** 17962, "The replication status for '%1!' is already set to %2!.
**	   Replication status for '%3!' does not change."
** 17964, "The replication status for '%1!' is set to %2!."
** 17965, "The replication status for '%1!' is currently %2!."
** 17966, "Due to system failure, the replication status for '%1!' has
**	   not been changed."
** 17967, "Only the System Administrator (SA), the Database Owner (dbo) or
**	   a user with REPLICATION authorization may execute this stored
**	   procedure."
** 18109, "Usage: sp_setrepcol table_name, column_name,
**						 {do_not_replicate |
**						  always_replicate |
**						  replicate_if_changed}"
** 18110, "The table '%1!' is not marked for replication."
** 18111, "do_not_replicate"
** 18112, "always_replicate"
** 18113, "replicate_if_changed"
** 18114, "A table name must be provided."
** 18115, "No Text/Image columns in '%1!'."
** 18116, "The replication status for all Text/Image columns
**	   in '%1!' is set to %2!."
** 18117, "Column '%1!' does not exist in '%2!' or is not a Text/Image column."
** 18118, "Object '%1!' does not exist in this database."
*/
create procedure sp_setrepcol
@replicate_name	varchar(92) = NULL,	/* table for the column */
@column_name	varchar(92) = NULL,	/* column we want to mark */
@setflag 	varchar(22) = NULL	/* the replicate status. */
as

declare @current_status	smallint /* current sysstat value for the object. */
declare @new_status	smallint /* new sysstat value for the object. */
declare @rep_constant 	smallint /* bit which indicates a replicated object. */
declare @dbccbit	int	 /* The "on"/"off" bit for the DBCC command */
declare @db		varchar(30) 	/* db of object. */
declare @owner		varchar(30) 	/* owner of object. */
declare @object		varchar(30)	/* object's name. */
declare @true		varchar(10)
declare @false		varchar(10)
declare @msg 		varchar(200)
declare @tmpstr		varchar(10)
declare @sptlang	int
declare @procval	int
declare @rnever	smallint
declare @ralways	smallint
declare @rifchanged	smallint
declare @rcolbitmask	smallint
declare @repnever	varchar(30)
declare @repalways	varchar(30)
declare @repifchanged	varchar(30)
declare @colid		smallint
declare @objid		int
declare @flag		varchar(255)
declare @lsetflag	varchar(22)
declare @texttype	smallint
declare @imagetype	smallint

if @@trancount = 0
begin
	set transaction isolation level 1
	set chained off
end

/*
** Replication enabled flag is 8000H (which is -32768D)
*/
select @rep_constant = -32768,
	@rnever = 0,
	@ralways = 1,
	@rifchanged = 2,
	@rcolbitmask = 3,
	@imagetype = 34,
	@texttype = 35

/*
** Initialize strings
*/
/* 18111, "do_not_replicate" */
exec sp_getmessage 18111, @repnever out
/* 18112, "always_replicate" */
exec sp_getmessage 18112, @repalways out
/* 18113, "replicate_if_changed" */
exec sp_getmessage 18113, @repifchanged out

/* Create a temp table for messages */
create table #setrepcol (val int, str varchar(255))
insert into #setrepcol values(@ralways, @repalways)
insert into #setrepcol values(@rnever, @repnever)
insert into #setrepcol values(@rifchanged, @repifchanged)

/*
** Set 'sptlang' for proper printing of object information.  Used mainly
** for the 'select' statement which is executed when we are invoked with
** no parameters.  Copied from similar code in 'sp_help'
*/
select @sptlang = @@langid
if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17100 and 17109
		and langid = @@langid)
	    select @sptlang = 0
end

if (@replicate_name is NULL)
begin
	/*
	** 18114, "A table name must be provided."
	*/
        exec sp_getmessage 18114, @msg output
        print @msg
	return (1)
end
/*
** Crack the name into its corresponding pieces.
*/
execute sp_namecrack 	@replicate_name, 
			@db = @db output, 
			@owner = @owner output,
			@object = @object output

/*
** Make sure that the object is in the current database.
*/
if (@db is not NULL and @db != db_name())
begin
	/*
	** 17460, "Object must be in the current database."
	*/
        exec sp_getmessage 17460, @msg output
        print @msg
	return (1)
end

/*
**  Make sure that the object actually exists.
*/
if (object_id(@replicate_name) is NULL)
begin
	/*
	** 18118, "Object '%1!' does not exist in this database."
	*/
	exec sp_getmessage 18118, @msg output
	print @msg, @replicate_name
	return (1)
end

/*
** Check if the object is a table.
*/
if not exists (
	select id from sysobjects 
	where
		id = object_id(@replicate_name) and
		type = "U")
begin
	/*
	** 18114, "A table name must be provided."
	*/
        exec sp_getmessage 18114, @msg output
        print @msg
	return (1)
end
/*
** Check if the table is marked for replication.
*/
select @current_status = sysstat 
	from sysobjects
	where id = object_id(@replicate_name)

/*
** Is the replicate status bit even set?
*/
if (@current_status & @rep_constant) = 0
begin
	/*
	** 18110, "The object '%1!' is not marked for replication."
	*/
	exec sp_getmessage 18110, @msg output
	print @msg, @replicate_name
	return(1)
end

if (@column_name is not NULL)
begin
	if not exists (select colid from syscolumns
			   where name = @column_name
				 and id = object_id(@replicate_name)
				 and type in (@imagetype, @texttype))
	begin
		/*
		** 18117 "Column '%1!' does not exist in '%2!' or is not
		** 	  a Text/Image column."
		*/
		exec sp_getmessage 18117, @msg output
		print @msg, @column_name, @replicate_name
		return(1)
	end
end
else
begin
	if not exists (select colid from syscolumns
			   where id = object_id(@replicate_name)
				 and type in (@imagetype, @texttype))
	begin
		/*
		** 18115 "No Text/Image columns in '%1!'."
		*/
		exec sp_getmessage 18115, @msg output
		print @msg, @replicate_name
		return(1)
	end
end

/*
** If we are invoked with two parameters, then just print out status
*/
if (@setflag is NULL)
begin
	if (@column_name is NULL)
	begin
		select
			Name = c.name,
			Type = convert(char(5),t.name),
			Status = convert(char(22), s.str)
		from
			syscolumns c holdlock,
			systypes t,
			#setrepcol s
		where 
			c.id = object_id(@replicate_name)
			and c.type in (@imagetype, @texttype)
			and c.type = t.type
			and s.val = (c.status & @rcolbitmask)
	end
	else
	begin
		select
			Name = c.name,
			Type = convert(char(5), t.name),
			Status = convert(char(22), s.str)
		from
			syscolumns c holdlock,
			systypes t,
			#setrepcol s
		where 
			c.id = object_id(@replicate_name)
			and c.name = @column_name
			and c.type in (@imagetype, @texttype)
			and c.type = t.type
			and s.val = (c.status & @rcolbitmask)
	end
	return (0)
end

/*
** Check for a valid setname parameter
*/
if (lower(@setflag) not in ("do_not_replicate", "always_replicate",
			    "replicate_if_changed", @repnever,
			    @repalways, @repifchanged))
begin
	/*
	** 18109, "Usage: sp_setrepcol table_name, column_name,	
	**					{do_not_replicate |
	**					 always_replicate |
	**					 replicate_if_changed}"
	*/
	exec sp_getmessage 18109, @msg output
	print @msg
	return (1)
end

/*
** You must be SA, dbo or have REPLICATION role to execute this
** sproc.
*/
if (user_id() = 1)
begin
	/*
	** If we have SA role, then we may not be the "real"
	** database owner and may have assumed the identity of the
	** database owner through our SA role privileges.  If
	** this is the case, we should audit an SA role success
	** to audit the fact that SA role privileges were needed
	** to run these commands.
	*/
	if charindex("sa_role", show_role()) > 0
	begin
		select @procval = proc_role("sa_role")
	end
end
else
begin
	if (proc_role("sa_role") != 1)
	begin
		/*
		** 17967, "Only the System Administrator (SA), the
		**	   Database Owner (dbo) or a user with REPLICATION
		**	   authorization may execute this stored
		**	   procedure."
		*/
		exec sp_getmessage 17967, @msg output
		print @msg
		return (1)
	end
end

/*
** Perform the requested operation on the object.
*/
select @objid = object_id(@replicate_name)
select @lsetflag = lower(@setflag)

if @lsetflag in ("always_replicate", @repalways)
begin
	if (@column_name is NULL)
	begin
	   begin transaction
		select @colid = min(colid) from syscolumns
		where
			id = @objid
			and type in (@imagetype, @texttype)
		while (@colid is not NULL)
		begin
			dbcc replicate_txtcol(@objid, @colid, @lsetflag)
			if @@error != 0
			begin
				/*
				** 17966 "Due to system failure, the 
				**        replication status for '%1!' has
				**	  not been changed."
				*/
				exec sp_getmessage 17966, @msg output
				print @msg, @replicate_name, @lsetflag

				rollback transaction

				return (1)
			end
				
			select @colid = min(colid) from syscolumns
			where
				id = @objid
				and type in (@imagetype, @texttype)
				and colid > @colid
		end
	  commit transaction
	end
	else
	begin
		select @colid = colid from syscolumns
		where
			name = @column_name
			and id = @objid

		dbcc replicate_txtcol(@objid, @colid, @lsetflag)
		if @@error != 0
		begin
			/*
			** 17966 "Due to system failure, the 
			**        replication status for '%1!' has
			**	  not been changed."
			*/
			exec sp_getmessage 17966, @msg output
			print @msg, @replicate_name, @lsetflag

			return (1)
		end
	end
end
else 
/* flag is either repnever or repifchanged */
begin
	if (@column_name is NULL)
	begin
	   begin transaction
		/* Set the status for all text/image columns */
		select @colid = min(colid) from syscolumns
		where
			id = @objid
			and type in (@imagetype, @texttype)
		while (@colid is not NULL)
		begin
			dbcc replicate_txtcol(@objid, @colid, @lsetflag)
			if @@error != 0
			begin
				/*
				** 17966 "Due to system failure, the 
				**        replication status for '%1!' has
				**	  not been changed."
				*/
				exec sp_getmessage 17966, @msg output
				print @msg, @replicate_name, @lsetflag

				rollback transaction

				return (1)
			end

			select @colid = min(colid) from syscolumns
			where
				id = @objid
				and type in (@imagetype, @texttype)
				and colid > @colid
		end
	   commit transaction
	end
	else
	begin
		/* Set the status for the given column */
		select @colid = colid from syscolumns
		where
			id = @objid and 
			name = @column_name

		dbcc replicate_txtcol(@objid, @colid, @lsetflag)
		if @@error != 0
		begin
			/*
			** 17966 "Due to system failure, the 
			**        replication status for '%1!' has
			**	  not been changed."
			*/
			exec sp_getmessage 17966, @msg output
			print @msg, @replicate_name, @lsetflag

			return (1)
		end
	end
end

if (@column_name is NULL)
begin
	/*
	** 18116, "The replication status for all Text/Image columns 
	**         in '%1!' is set to %2!."
	*/
	exec sp_getmessage 18116, @msg output
	print @msg, @replicate_name, @setflag
	return(0)
end
else
begin
	/*
	** 17964 "The replication status for '%1!' is set to %2!."
	*/
	exec sp_getmessage 17964, @msg output
	print @msg, @column_name, @setflag
	return(0)
end
go
exec sp_procxmode 'sp_setrepcol', 'anymode'
go
grant execute on sp_setrepcol to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setrepproc')
begin
	drop procedure sp_setrepproc
end
go
print "Installing sp_setrepproc"
go

/* Sccsid = "@(#) generic/sproc/setreplicate 155.1 11/10/94" */
/*
** Messages for "sp_setreplicate"	17960
**
** 17230, "Only the System Administrator (SA) or the Database Owner
**	   (dbo) may execute this stored procedure."
** 17432, "false"
** 17962, "The replication status for '%1!' is already set to %2!.
**	   Replication status for '%3!' does not change."
** 17963, "A object with the same name, but owned by a different user
**	   is already being replicated.  The object '%1!' cannot be
**	   replicated."
** 17964, "The replication status for '%1!' is set to %2!."
** 17965, "The replication status for '%1!' is currently %2!."
** 17966, "Due to system failure, the replication status for '%1!' has
**	   not been changed."
** 17967, "Only the System Administrator (SA), the Database Owner (dbo) or
**	   a user with REPLICATION authorization may execute this stored
**	   procedure."
** 18104, "table"
** 18105, "function"
** 18106, "Stored Procedure must be in the current database."
** 18107, "Stored Procedure '%1!' does not exist in this database."
** 18108, "Usage: sp_setrepproc procedure_name, {function |
	   table | false}"
*/
create procedure sp_setrepproc
@replicate_name	varchar(92) = NULL,	/* obj we want to mark as replicate */
@setflag 	varchar(20) = NULL	/* set or unset the replicate status. */
as

declare @current_status	smallint /* current sysstat value for the object. */
declare @new_status	smallint /* new sysstat value for the object. */
declare @rep_constant 	smallint /* bit which indicates a replicated object. */
declare @sub_constant	smallint /* bit which indicates a function proc */
declare @dbccbit	int	 /* The "on"/"off" bit for the DBCC command */
declare @db		varchar(30) 	/* db of object. */
declare @owner		varchar(30) 	/* owner of object. */
declare @object		varchar(30)	/* object's name. */
declare @true		varchar(10)
declare @table		varchar(20)
declare @function	varchar(20)
declare @false		varchar(10)
declare @msg 		varchar(200)
declare @tmpstr		varchar(20)
declare @sptlang	int
declare @procval	int

if @@trancount = 0
begin
	set transaction isolation level 1
	set chained off
end

/*
** Replication enabled flag is 8000H (which is -32768D)
*/
select @rep_constant = -32768

/*
** Function flag is 40H in sysstat (which is 64D)
*/
select @sub_constant = 64

/*
** Initialize 'true' and 'false' strings
*/
/* 18104, "table" */
exec sp_getmessage 18104, @table out
/* 18105, "function" */
exec sp_getmessage 18105, @function out
/* 17432, "false" */
exec sp_getmessage 17432, @false out

/*
** Set 'sptlang' for proper printing of object information.  Used mainly
** for the 'select' statement which is executed when we are invoked with
** no parameters.  Copied from similar code in 'sp_help'
*/
select @sptlang = @@langid
if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17100 and 17109
		and langid = @@langid)
	    select @sptlang = 0
end

/*
** If we are invoked with no parameters, then just print out all procedures
** which are marked for replication.  The 'select' statement is heavily
** based upon the one found in 'sp_help'.
*/
if (@replicate_name is NULL and @setflag is NULL)
begin
	select
		Name = o.name,
		Type = convert(char(14), m.description)
	from
		sysobjects o,
		master.dbo.sysmessages m
	where 
		o.type = "P"		
		and 
		((
		(o.sysstat & @sub_constant) = @sub_constant
		and m.error = 18105 /* function */
		)
	or
		(
		(o.sysstat & @sub_constant) = 0
		and (o.sysstat & @rep_constant) = @rep_constant
		and m.error = 18104 /* table */
		))
	return (0)
end

/*
** Crack the name into its corresponding pieces.
*/
execute sp_namecrack 	@replicate_name, 
			@db = @db output, 
			@owner = @owner output,
			@object = @object output

/*
** Make sure that the object is in the current database.
*/
if (@db is not NULL and @db != db_name())
begin
	/*
	** 18106, "Procedure must be in the current database."
	*/
        exec sp_getmessage 18106, @msg output
        print @msg
	return (1)
end

/*
**  Make sure that the object actually exists.
*/
if (object_id(@replicate_name) is NULL)
	or (not exists (select name from sysobjects where 
		id = object_id(@replicate_name) and
		type = "P"
		))
begin
	/*
	** 18107, "Procedure does not exist in this database."
	*/
	exec sp_getmessage 18107, @msg output
	print @msg, @replicate_name
	return (1)
end

/*
** If the 'setflag' parameter is NULL, then we are only interested in the
** current replication status of the specified object.
*/
if (@setflag is NULL)
begin
	select
		@current_status = sysstat
	from 
		sysobjects holdlock
	where 
		id = object_id(@replicate_name)

	if (@current_status & @rep_constant) = @rep_constant
	begin
		if (@current_status & @sub_constant) = @sub_constant
		begin
			select @tmpstr = @function
		end
		else
		begin
			select @tmpstr = @table
		end
	end
	else
	begin
		select @tmpstr = @false
	end

	/*
	** 17965 "The replication status for '%1!' is currently %2!."
	*/
	exec sp_getmessage 17965, @msg output
	print @msg, @replicate_name, @tmpstr

	return (0)
end

/*
** You must be SA, dbo or have REPLICATION role to execute this
** sproc.
*/
if (user_id() = 1)
begin
	/*
	** If we have SA role, then we may not be the "real"
	** database owner and may have assumed the identity of the
	** database owner through our SA role privileges.  If
	** this is the case, we should audit an SA role success
	** to audit the fact that SA role privileges were needed
	** to run these commands.
	*/
	if charindex("sa_role", show_role()) > 0
	begin
		select @procval = proc_role("sa_role")
	end
end
else
begin
	if (proc_role("sa_role") != 1)
	begin
		/*
		** 17967, "Only the System Administrator (SA), the
		**	   Database Owner (dbo) or a user with REPLICATION
		**	   authorization may execute this stored
		**	   procedure."
		*/
		exec sp_getmessage 17967, @msg output
		print @msg
		return (1)
	end
end

/*
** Check for a valid setname parameter
*/
if (lower(@setflag) not in ("function", "table", "false", @function, @table, @false))
begin
	/*
	** 18108 "Usage: sp_setrepproc procedure_name, {function |
	**						 table | false}"
	*/
	exec sp_getmessage 18108, @msg output
	print @msg
	return (1)
end

/*
** Get the object's current status. Hold a read lock on sysobjects so that 
**	the status cannot be changed until we're done.
*/
select @current_status = sysstat
	from sysobjects holdlock
		where id = object_id(@replicate_name)

/*
** Perform the requested operation on the object.
*/
if lower(@setflag) in ("false", @false)
begin
	/*
	** Is the replicate status bit even set?
	*/
	if (@current_status & @rep_constant) = 0
	begin
		/*
		** 17962 "The replication status for '%1!' is already
		**	  set to %2!.  Replication status for '%3!'
		**	  does not change."
		*/
		exec sp_getmessage 17962, @msg output
		print @msg, @replicate_name, @setflag, @replicate_name
		return(1)
	end

	select @new_status = @current_status & ~(@rep_constant
					| @sub_constant)
	select @dbccbit = 0
end
else if lower(@setflag) in ("table", @table)
begin
	/*
	** Is the replicate status bit already set?
	*/
	if (((@current_status & @rep_constant) != 0) and 
		(@current_status & @sub_constant) = 0)
	begin
		/*
		** 17962 "The replication status for '%1!' is already
		**	  set to %2!.  Replication status for '%3!'
		**	  does not change."
		*/
		exec sp_getmessage 17962, @msg output
		print @msg, @replicate_name, @setflag, @replicate_name
		return(1)
	end

	/*
	** Make sure that no like object with the same name, but a
	** different owner, exists.  We need to do this because
	** the SQL Server does not send owner information along
	** with the object to the Replication Server.  This
	** restriction may be lifted in future versions.
	*/
	if exists (select * from sysobjects
			where name = @object
			and id != object_id(@replicate_name)
			and (
				(type = "U ") /* user table */
			or
				(type = "P ") /* stored procedure */
			)
			and sysstat & @rep_constant != 0)
	begin
		/*
		** 17963 "An object with the same name, but owned by a
		**	  different user is already being replicated.
		**	  The object '%1!' cannot be replicated."
		*/
		exec sp_getmessage 17963, @msg output
		print @msg, @replicate_name
		return(1)
	end

	select @new_status = (@current_status | @rep_constant)
				& ~@sub_constant
	select @dbccbit = 1
end
else if lower(@setflag) in ("function", @function)
begin
	/*
	** Is the replicate status bit already set?
	*/
	if (@current_status & @sub_constant) = @sub_constant
	begin
		/*
		** 17962 "The replication status for '%1!' is already
		**	  set to %2!.  Replication status for '%3!'
		**	  does not change."
		*/
		exec sp_getmessage 17962, @msg output
		print @msg, @replicate_name, @setflag, @replicate_name
		return(1)
	end

	/*
	** Make sure that no like object with the same name, but a
	** different owner, exists.  We need to do this because
	** the SQL Server does not send owner information along
	** with the object to the Replication Server.  This
	** restriction may be lifted in future versions.
	*/
	if exists (select id from sysobjects
			where name = @object
			and id != object_id(@replicate_name)
			and (
				(type = "U ") /* user table */
			or
				(type = "P ") /* stored procedure */
			)
			and sysstat & @rep_constant != 0)
	begin
		/*
		** 17963 "An object with the same name, but owned by a
		**	  different user is already being replicated.
		**	  The object '%1!' cannot be replicated."
		*/
		exec sp_getmessage 17963, @msg output
		print @msg, @replicate_name
		return(1)
	end

	select @new_status = @current_status | @rep_constant
					| @sub_constant
	select @dbccbit = 2
end

/*
** Update the object's sysstat column
*/
begin transaction

	update sysobjects
		set sysstat = @new_status
			where id = object_id(@replicate_name)

	/*
	** Update the object's status in cache.
	*/
	dbcc setrepstatus("procedure",@replicate_name, @dbccbit)

	if @@error != 0
	begin
		/*
		** 17966 "Due to system failure, the replication status
		**	  for '%1!' has not been changed."
		*/
		exec sp_getmessage 17966, @msg output
		print @msg, @replicate_name, @setflag

		rollback transaction

		return (1)
	end

commit transaction

/*
** 17964 "The replication status for '%1!' is set to %2!."
*/
exec sp_getmessage 17964, @msg output
print @msg, @replicate_name, @setflag
return(0)
go
exec sp_procxmode 'sp_setrepproc', 'anymode'
go
grant execute on sp_setrepproc to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setreptable')
begin
	drop procedure sp_setreptable
end
go
print "Installing sp_setreptable"
go

/* Sccsid = "@(#) generic/sproc/setreplicate 155.1 11/10/94" */
/*
** Messages for "sp_setreptable"	17960
**
** 17230, "Only the System Administrator (SA) or the Database Owner
**	   (dbo) may execute this stored procedure."
** 17431, "true"
** 17432, "false"
** 17962, "The replication status for '%1!' is already set to %2!.
**	   Replication status for '%3!' does not change."
** 17964, "The replication status for '%1!' is set to %2!."
** 17965, "The replication status for '%1!' is currently %2!."
** 17966, "Due to system failure, the replication status for '%1!' has
**	   not been changed."
** 17967, "Only the System Administrator (SA), the Database Owner (dbo) or
**	   a user with REPLICATION authorization may execute this stored
**	   procedure."
** 18100, "Usage: sp_setreptable table_name, {true | false}"
** 18101, "Table must be in the current database."
** 18102, "Table '%1!' does not exist in this database."
** 18103, "An object with the same name, but owned by a different user
**	   is already being replicated.  The table '%1!' cannot be
**	   replicated."
*/
create procedure sp_setreptable
@replicate_name	varchar(92) = NULL,	/* obj we want to mark as replicate */
@setflag 	varchar(5) = NULL	/* set or unset the replicate status. */
as

declare @current_status	smallint /* current sysstat value for the object. */
declare @new_status	smallint /* new sysstat value for the object. */
declare @rep_constant 	smallint /* bit which indicates a replicated object. */
declare @colrepalwys	smallint
declare @dbccbit	int	 /* The "on"/"off" bit for the DBCC command */
declare @db		varchar(30) 	/* db of object. */
declare @owner		varchar(30) 	/* owner of object. */
declare @object		varchar(30)	/* object's name. */
declare @true		varchar(10)
declare @false		varchar(10)
declare @msg 		varchar(200)
declare @tmpstr		varchar(10)
declare @sptlang	int
declare @procval	int
declare @texttype	smallint
declare @imagetype	smallint
declare @objid		int
if @@trancount = 0
begin
	set transaction isolation level 1
	set chained off
end

/*
** Replication enabled flag is 8000H (which is -32768D)
*/
select @rep_constant = -32768,
	@colrepalwys  = 1,
	@imagetype = 34,
	@texttype = 35

/*
** Initialize 'true' and 'false' strings
*/
/* 17431, "true" */
exec sp_getmessage 17431, @true out
/* 17432, "false" */
exec sp_getmessage 17432, @false out

/*
** Set 'sptlang' for proper printing of object information.  Used mainly
** for the 'select' statement which is executed when we are invoked with
** no parameters.  Copied from similar code in 'sp_help'
*/
select @sptlang = @@langid
if @@langid != 0
begin
	if not exists (
		select * from master.dbo.sysmessages where error
		between 17100 and 17109
		and langid = @@langid)
	    select @sptlang = 0
end

/*
** If we are invoked with no parameters, then just print out all objects
** which are marked for replication.  The 'select' statement is heavily
** based upon the one found in 'sp_help'.
*/
if (@replicate_name is NULL and @setflag is NULL)
begin
	select
		Name = o.name
	from
		sysobjects o
	where 
		o.type = "U"
		and (o.sysstat & @rep_constant) = @rep_constant

	return (0)
end

/*
** Crack the name into its corresponding pieces.
*/
execute sp_namecrack 	@replicate_name, 
			@db = @db output, 
			@owner = @owner output,
			@object = @object output

/*
** Make sure that the object is in the current database.
*/
if (@db is not NULL and @db != db_name())
begin
	/*
	** 18101, "Table must be in the current database."
	*/
        exec sp_getmessage 18101, @msg output
        print @msg
	return (1)
end

/*
**  Make sure that the object actually exists.
*/
if (object_id(@replicate_name) is NULL) or
	(not exists (select name from sysobjects where 
		id = object_id(@replicate_name) and
		type = "U"
		))
begin
	/*
	** 18102, "Table '%1!' does not exist in this database."
	*/
	exec sp_getmessage 18102, @msg output
	print @msg, @replicate_name
	return (1)
end

/*
** If the 'setflag' parameter is NULL, then we are only interested in the
** current replication status of the specified object.
*/
if (@setflag is NULL)
begin
	select
		@current_status = sysstat
	from 
		sysobjects holdlock
	where 
		id = object_id(@replicate_name)

	if (@current_status & @rep_constant) = @rep_constant
	begin
		select @tmpstr = @true
	end
	else
	begin
		select @tmpstr = @false
	end

	/*
	** 17965 "The replication status for '%1!' is currently %2!."
	*/
	exec sp_getmessage 17965, @msg output
	print @msg, @replicate_name, @tmpstr

	return (0)
end

/*
** You must be SA, dbo or have REPLICATION role to execute this
** sproc.
*/
if (user_id() = 1)
begin
	/*
	** If we have SA role, then we may not be the "real"
	** database owner and may have assumed the identity of the
	** database owner through our SA role privileges.  If
	** this is the case, we should audit an SA role success
	** to audit the fact that SA role privileges were needed
	** to run these commands.
	*/
	if charindex("sa_role", show_role()) > 0
	begin
		select @procval = proc_role("sa_role")
	end
end
else
begin
	if (proc_role("sa_role") != 1)
	begin
		/*
		** 17967, "Only the System Administrator (SA), the
		**	   Database Owner (dbo) or a user with REPLICATION
		**	   authorization may execute this stored
		**	   procedure."
		*/
		exec sp_getmessage 17967, @msg output
		print @msg
		return (1)
	end
end

/*
** Check for a valid setname parameter
*/
if (lower(@setflag) not in ("true", "false", @true, @false))
begin
	/*
	** 18100 "Usage: sp_setreptable table_name, {true | false}"
	*/
	exec sp_getmessage 18100, @msg output
	print @msg
	return (1)
end

/*
** Get the object's current status. Hold a read lock on sysobjects so that 
**	the status cannot be changed until we're done.
*/
select @current_status = sysstat 
	from sysobjects holdlock
		where id = object_id(@replicate_name)

/*
** Perform the requested operation on the object.
*/
if lower(@setflag) in ("false", @false)
begin
	/*
	** Is the replicate status bit even set?
	*/
	if (@current_status & @rep_constant) = 0
	begin
		/*
		** 17962 "The replication status for '%1!' is already
		**	  set to %2!.  Replication status for '%3!'
		**	  does not change."
		*/
		exec sp_getmessage 17962, @msg output
		print @msg, @replicate_name, @setflag, @replicate_name
		return(1)
	end

	select @new_status = @current_status & ~@rep_constant
	select @dbccbit = 0
end
else
begin
	/*
	** Is the replicate status bit already set?
	*/
	if (@current_status & @rep_constant) != 0
	begin
		/*
		** 17962 "The replication status for '%1!' is already
		**	  set to %2!.  Replication status for '%3!'
		**	  does not change."
		*/
		exec sp_getmessage 17962, @msg output
		print @msg, @replicate_name, @setflag, @replicate_name
		return(1)
	end

	/*
	** Make sure that no like object with the same name, but a
	** different owner, exists.  We need to do this because
	** the SQL Server does not send owner information along
	** with the object to the Replication Server.  This
	** restriction may be lifted in future versions.
	*/
	if exists (select * from sysobjects
			where name = @object
			and (
				(type = "U ") /* user table */
			or
				(type = "P ") /* stored procedure */
			)
			and sysstat & @rep_constant != 0)
	begin
		/*
		** 18103 "An object with the same name, but owned by a
		**	  different user is already being replicated.
		**	  The table '%1!' cannot be replicated."
		*/
		exec sp_getmessage 18103, @msg output
		print @msg, @replicate_name
		return(1)
	end

	select @new_status = @current_status | @rep_constant
	select @dbccbit = 1
end

/*
** Update the object's sysstat column
*/
begin transaction
	

	/* Update the column bits for text/image columns */

	select @objid = object_id(@replicate_name)
	update sysobjects set sysstat = @new_status
	where
		id = @objid
	if (@dbccbit = 1)
	begin
		update syscolumns set status = status|@colrepalwys
		where
			id = @objid
			and type in (@imagetype, @texttype)
	end
	/*
	** Update the object's status in cache.
	*/
	dbcc setrepstatus("table",@replicate_name, @dbccbit)

	if @@error != 0
	begin
		/*
		** 17966 "Due to system failure, the replication status
		**	  for '%1!' has not been changed."
		*/
		exec sp_getmessage 17966, @msg output
		print @msg, @replicate_name, @setflag

		rollback transaction

		return (1)
	end

commit transaction

/*
** 17964 "The replication status for '%1!' is set to %2!."
*/
exec sp_getmessage 17964, @msg output
print @msg, @replicate_name, @setflag
return(0)
go
exec sp_procxmode 'sp_setreptable', 'anymode'
go
grant execute on sp_setreptable to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_logiosize')
begin
	drop procedure sp_logiosize
end
go
print "Installing sp_logiosize"
go

/* Stored procedure for setting the log I/O size. */

/*
** Messages for sp_logiosize
**
** 17260, "Can't run %1! from with in a transaction."
** 17289, "Set your curwrite to the hurdle of current database."
** 18126, "Log I/O Size must be a power of 2. 
**	   For example: 2, 4, 8 and  16"
** 18127, "You must have System Administrator (SA) role to 
**	   execute this stored procedure." 
** 18128, "Unable to change the log I/O size. The memory pool 
**	   for the specified log I/O size does not exist." 
** 18129, "Log I/O size is set to %1! Kbytes."
** 18130, "sp_logiosize failed.  Please contact Sybase Technical 
**	   Support to help you resolve the problem."
** 18131, "Log I/O Size value '%1!' is illegal."
** 18132, "The transaction log for database '%1!' will use I/O size of %2! 
**	   Kbytes."
*/

/*
** Syntax:
**
** sp_logiosize ["default" | "value" | "all"]
** 
** Internal variables used:
**
**	@old_value - The log I/O size from the sysattributes if it exists.
**	@new_value - The log I/O size specified through sp_logiosize.
**	@use_value - The log I/O size server would use based on available
**		     resources.
**	@action	   - Denotes add, change, drop or fetch an I/O size value.
**
**	Handle the following 3 cases for @new_value
**		case NULL
**		case @new_value > 0
**		case @new_value = "default"
*/

create procedure sp_logiosize
@size		varchar(30) = NULL
as
declare	@new_value	int
declare	@objid		int
declare	@old_value	int
declare @action		int 
declare @use_value	int
declare @tempiosize	int
declare @retstat	int
declare @row_count	int
declare @cstat		int
declare @msg            varchar(255)
declare @tempstr	varchar(30)
declare @dbname		varchar(30)
declare @name                   varchar(30)/* cache name from sysconfigures */
/* 
** Extract the I/O size value from the input.
*/

select @tempstr = lower(ltrim(rtrim(@size)))

if @tempstr is NULL
begin
	select @new_value =  NULL
end
else
begin
	/* Check whether the input value is an integer */
	if @tempstr like "[0-9]%"
	begin
		select @new_value = convert(int , @tempstr)
		/* 
		** Make sure the log I/O size is a power of 2 and is 
		** between @@pagesize to 8 * @@pagesize. 
		*/

		select @tempiosize = @@pagesize / 1024
		while @tempiosize < @new_value
			select @tempiosize = @tempiosize * 2
		if @tempiosize != @new_value
			or @tempiosize > 8 * @@pagesize / 1024
			or @tempiosize < @@pagesize / 1024
		begin
			/*
			** 18126, "Log I/O Size must be a power of 2. 
			** For example: 2, 4, 8 and 16."
			*/
			exec sp_getmessage 18126, @msg output
			print @msg
			return(1)
		end
	end
	else
	/* Process the value as a character string */
	begin
		/* Check whether the input value is "default" */
		if @tempstr = "default"
		begin
			select @new_value = 0
		end
		else if @tempstr = "all"
		begin
			/* 
			** Ther is no sanctity about this value.  We just
			** want to differentiate this value from other
			** valid values.  This indicates that user wants
			** log I/O size listing for all data bases.
			*/
			select @new_value = 99
		end
		else
		begin
			/*
			** 18131, "Log I/O Size value '%1!' is illegal."
			*/
			exec sp_getmessage 18131, @msg output
			print @msg, @size
			return(1)
		end
	end
end

/*
** Don't allow this in a transaction because we can't undo what 
** we have done through the attr_notify() built-in.
*/
if @@trancount >0
begin
	/*
	** 17260, "Can't run %1! from with in a transaction."
	*/				
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_logiosize"
	return(1)
end
else
begin
	set transaction isolation level 1
	set chained off
end

select @objid = object_id("syslogs")
select @dbname = db_name()
select @use_value = 0

/* 
** If the input value is NULL, print the log I/O size set for the current
** database.
*/
if @new_value is NULL
begin
	/* 
	** Print the log I/O size set for the current database 
	*/
	select @action = 4 /* Denotes fetching a value */
	select @use_value = attrib_notify(2,0,"T",@objid,NULL,NULL,
					NULL,NULL,@new_value,NULL,NULL,
					NULL,NULL,@action)
end

else if @new_value = 99
begin
	/* List log I/O size values for all the data bases */

	select name into #syscacheconfig from master.dbo.sysconfigures
		where parent = 19 and config = 19	
	/*
	**  Find out the number of rows we want to look at.
	*/
	select @row_count = count(*) from #syscacheconfig
	
	declare logiosize_cursor cursor
	for select name from #syscacheconfig
 
	open logiosize_cursor

	while (@row_count > 0)
	begin
		fetch logiosize_cursor into @name
		print "Cache name: %1!", @name
		print "Data base                       Log I/O Size" 
		print "------------------------------  ------------"
		select @cstat = config_admin(9, 4, 0, 0, NULL, @name)
		print " "
		select @row_count = @row_count - 1
	end

	close logiosize_cursor
	return(0)
end
/* 
** Process other input values.  Look for a matching row in the 
** sysattributes table for the Log I/O Size attribute.
*/
else
begin
	/* 
	** Check if user has "sa" role. proc_role() also does auditing 
	** if required.  proc_role() will also print error message if 
	** required.
	*/
	if (proc_role("sa_role") = 0)
	begin
		/*
		** 18127, "You must have System Administrator (SA) role 
		** to execute this stored procedure." 
		*/
		exec sp_getmessage 18127, @msg output
		print @msg
		return(1)
	end



	select @old_value = int_value  from sysattributes 
			where 	class 		= 2 	and
				attribute 	= 0 	and
				object 		= @objid

	/* We found a matching entry in sysattributes */

	if @old_value != 0 and @old_value is not NULL
	begin 
		if @new_value > 0
		begin
		
			select @action = 2 /* Denotes a change */

			/* If the previous Log I/O Size value is same as the 
			** requested value do not do any thing. Otherwise update
			** the value.
			*/
		
			if @new_value = @old_value
			begin
				select @use_value = @old_value
			end
			else
			begin
				select @use_value = attrib_notify(2,0,"T",
					@objid,NULL,NULL,NULL,NULL,@new_value,
					NULL,NULL,NULL,NULL,@action)
				if @use_value = @new_value
				begin
					update sysattributes 
					set int_value = @new_value 
					where 	class 	= 2 	and
					attribute 	= 0 	and
					object 		= @objid
				end
			end
		end

		if @new_value = 0	/* Handles "default" value */
		begin
			select @action = 3 /* Denotes a drop */
			select @use_value = attrib_notify(2,0,"T",
				@objid,NULL,NULL,NULL,NULL,@new_value,NULL, 
				NULL,NULL,NULL,@action)
			/* Delete the entry from sysattributes */
			delete sysattributes 
			where 	class 	= 2 	and
			attribute 	= 0 	and
			object 		= @objid
		end

	end

	else

	/* There are no entries in the sysattributes table. */
	begin
		/* We did not find a matching entry.  So insert a new entry */
		if @new_value > 0 
		begin
			/* 
			** First check whether specified buffer pool exists.
			** It it does, then insert the row.
			*/
		
			select @action = 1 /* Denotes an addition of a row */
			select @use_value = attrib_notify(2,0,"T",
				@objid,NULL,NULL,NULL,NULL,@new_value,NULL,
				NULL,NULL,NULL,@action)
			if @use_value = @new_value
			begin
				/* Insert an entry in sysattributes */
				insert sysattributes(class, attribute, 
					object_type, object, int_value)
					values(2, 0, 'T', @objid, @new_value)
			end
		end

		if @new_value = 0 	/* Handles "default" value */
		begin
			/* 
			** The action taken is same as @action = 3 above
			** except we dont have any row to delete.
			*/
			select @action = 3 
			select @use_value = attrib_notify(2,0,"T",
				@objid,NULL,NULL,NULL,NULL,@new_value,NULL,
				NULL,NULL,NULL,@action)
		end
	end
end

/* 
** Process the return values from the attrib_notify built-in function.
** @use_value = 0 denotes that sysattributes notification has failed.
*/

if (@use_value = 0)
begin
	/*
	** 18130, "sp_logiosize failed.  Please contact Sybase 
	** Technical Support to help you resolve the problem."
	*/
	exec sp_getmessage 18130, @msg output
	print @msg
	return(1)
end 

/*
** @action = 1  Qualified for an addition of row in sysattributes 
** @action = 2  Qualified for a change of row in sysattributes 
** @action = 3  Qualified for a deletion of row in sysattributes 
** @action = 4  Fetched a log I/O size value 
*/

if (@action = 1) or (@action = 2)
begin
	if @use_value = @new_value
	begin
		/*
		** 18129, "Log I/O size is set to %1! Kbytes."
		** 18132, "The transaction log for database '%1!' will use 
		** 	   I/O size of %2! Kbytes."
		*/
		exec sp_getmessage 18129, @msg output
		print @msg, @new_value
		exec sp_getmessage 18132, @msg output
		print @msg, @dbname, @use_value
	end
	else
	begin
		/*
		** 18128, "Unable to change the log I/O size. 
		** The buffer pool for the specified log I/O size 
		** does not exist." 
		*/
		exec sp_getmessage 18128, @msg output
		print @msg
	end
end
else if (@action = 3)
begin
	/*
	** 18132, "The transaction log for database '%1!' will use 
	**         I/O size of %2! Kbytes."
	*/
	exec sp_getmessage 18132, @msg output
	print @msg, @dbname, @use_value
end
else if (@action = 4)
begin
	/*
	** 18129, "Log I/O size is set to %1! Kbytes."
	*/
	if @old_value != 0 and @old_value is not NULL
	begin
		/*
		** 18129, "Log I/O size is set to %1! Kbytes."
		*/
		exec sp_getmessage 18129, @msg output
		print @msg, @old_value
	end
	/*
	** 18132, "The transaction log for database '%1!' will use 
	**         I/O size of %2! Kbytes."
	*/
	exec sp_getmessage 18132, @msg output
	print @msg, @dbname, @use_value
end
else /* sp_logiosize failed */
begin
	/*
	** 18130, "sp_logiosize failed.  Please contact Sybase 
	** Technical Support to help you resolve the problem."
	*/
	exec sp_getmessage 18130, @msg output
	print @msg
end 
go
exec sp_procxmode 'sp_logiosize', 'anymode'
go
grant execute on sp_logiosize to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_helpcache')
begin
	drop procedure sp_helpcache
end
go
print "Installing sp_helpcache"
go

/* This stored procedure is for displaying cache overhead and bindings */
/* 17260, "Can't run %1! from within a transaction." */
/* 18174, "The database '%1!' is offline. To obtain cache-bindings for objects in this database, please online the database and rerun sp_helpcache. */

create procedure sp_helpcache
@parm1		varchar(30) = NULL
as

declare @stat			int	/* cache status from sysconfigures */
declare @cstat			int	/* status return from config_admin */
declare	@unit_loc		int	/* location of unit specifier in str */
declare	@size			int	/* cache size from sysconfigures */
declare	@row_count		int	/* # rows in #syscacheconfig */
declare	@config_size		int	/* cache's configured size 
					** (syscurconfigs
					*/ 
declare	@run_size		int	/* cache's current run size from 
					** syscurconfigs
					*/
declare @overhead		int	/* cache's memory overhead */
declare @total_config		int	/* total configured cache memory */
declare	@total_run		int	/* total running cache memory */
declare @total_overhead		int	/* total amount of overhead used */
declare @left_over_mem		int	/* memory not explicitly configuured */
declare @status2		int	/* Sysdatabase[DAT_STATUS2] */
declare	@first_char		char(1)	/* first char of parm1 */
declare	@unit			varchar(5) /* unit of size for configuration */
declare @name			varchar(30)/* cache name from sysconfigures */
declare @config_sz_str		varchar(30)/* str value for run_size */ 
declare @run_sz_str		varchar(30)/* str value for config_size */  
declare @overhead_sz_str	varchar(30)/* str value for overhead size */
declare @print_str		varchar(255)/* general string to print info */
declare @curr_avail_cache_mem	float	/* current amount of memory available
					** for named cache configuration.
					*/

/* Dont allow sp_helpcache to run with in a transaction. */
if @@trancount > 0
begin
	/*
	** 17260, "Can't run %1! from within a transaction."
	*/
	exec sp_getmessage 17260, @print_str output
	print @print_str, "sp_helpcache"
	return (1)
end
else
begin
	set transaction isolation level 1
	set chained off
end

select @first_char = substring(@parm1, 1, 1)

if (@parm1 = NULL or (patindex("%[a-z,A-Z]%", @first_char) != 0))
begin
	select name, value, value3, status
	into #syscacheconfig
	from master.dbo.sysconfigures
		where parent = 19 and name like "%" + @parm1 + "%"
		and config = 19	

	/*
	**  Find out the number of rows we want to look at.
	*/
	select @row_count = count(*) from #syscacheconfig
	
	/*
	**  If no rows qualify then this cache doesn't exist.
	*/
	if @row_count = 0
	begin
		exec sp_getmessage 18135, @print_str output
		print @print_str, @parm1
		return 1
	end

	declare sysc_cursor cursor
	for select name, value, status
		from #syscacheconfig
 
	open sysc_cursor

	print "Cache Name                Config Size     Run Size       Overhead"
	print "------------------------ -------------   ----------     ----------   "

	select @total_config = 0
	select @total_run = 0
	select @total_overhead = 0

	while (@row_count > 0)
	begin
		fetch sysc_cursor into @name, @size, @stat
		
		if (@stat & 32 = 32)
		begin
			select @config_size = @size
			select @total_config = @total_config + @config_size
			/*
			**  The actual run size is in syscurconfigs
			*/
			select @run_size = value, @overhead =  memory_used
			from master.dbo.syscurconfigs 
				where config=19 and 
				comment = @name
			select @total_run = @total_run + @run_size
		end
		if (@stat & 64 = 64)
		begin
			select @run_size = 0
			select @overhead = 0
			select @config_size = @size
			select @total_config = @total_config + @config_size
		end
		if (@stat & 128 = 128)
		begin
			/*
			**  The actual run size is in syscurconfigs
			*/
			select @run_size = value, @overhead = memory_used
			from master.dbo.syscurconfigs 
				where config=19 and 
				comment = @name
			select @config_size = 0
			select @total_run = @total_run + @run_size
		end	       
		
		select @total_overhead = @total_overhead + @overhead
		/*
		**  Convert run_size ,config_size and overhead to megabyte 
		**  values stored as strings
		*/
		select @run_sz_str = rtrim(str(convert(float,@run_size) / 1024, 7, 2)) + " Mb"
		select @config_sz_str = rtrim(str(convert(float,@config_size) / 1024, 7, 2)) + " Mb"
		select @overhead_sz_str = rtrim(str(convert(float,@overhead) / 1024, 7, 2)) + " Mb"
		
		select @print_str =  convert(char(25), @name) + convert(char(15), @config_sz_str) + convert(char(15), @run_sz_str) + convert(char(15), @overhead_sz_str)
		print @print_str

		select @row_count = @row_count - 1
	end

	close sysc_cursor

	/*
	**  If we're doing a helpcache on a specific cache then don't print
	**  out info on global memory availability.
	*/
	if patindex("%[a-z]%", @first_char) = 0
	begin
		select @curr_avail_cache_mem = 
				config_admin(13, 0, 0, 0, NULL, NULL)
		/*
		**  Subtract all cache overhead from available cache
		**  memory.
		*/
		select @curr_avail_cache_mem = @curr_avail_cache_mem - 
				@total_overhead
	
		print " "
		print " "
		print "Memory Available For      Memory Configured"
		print "Named Caches              To Named Caches"
		print "--------------------       ----------------"
		select @print_str =  convert(char(28), str(convert(float,@curr_avail_cache_mem) / 1024, 7, 2) + " Mb") + str(convert(float,@total_config) / 1024, 7, 2) + " Mb"
		print @print_str
		print " "
		select @left_over_mem = @curr_avail_cache_mem - @total_config
		if @left_over_mem > 0
		begin
			select @print_str = "There is " + str(convert(float,@left_over_mem) / 1024, 7, 2) + " Mb of memory left over that will be allocated to the default cache"
			print @print_str
		end
		print " "
	end


	print " "
	print "------------------ Cache Binding Information: ------------------ "
	print " "

	/*
	**  Find out the number of rows we want to look at.
	*/
	select @row_count = count(*) from #syscacheconfig
	
	declare bindings_cursor cursor
	for select name from #syscacheconfig
 
	open bindings_cursor

	print "Cache Name           Entity Name                Type               Index Name                    Status"
	print "----------           -----------                ----               ----------                    ------"
	while (@row_count > 0)
	begin
		fetch bindings_cursor into @name
		
		select @cstat = config_admin(9, 2, 0, 0, NULL, @name)

		select @row_count = @row_count - 1
	end

	close bindings_cursor

	/* Now print error message for offline databases. The built-in
	** function config_admin() ignores offline databases and we handle
	** them here after all online databases have been handled.  
	*/
	select name, status2
        into #sysdb
        from master.dbo.sysdatabases

	/*
	**  Find out the number of rows we want to look at.
	*/
	select @row_count = count(*) from #sysdb
	
	declare offlinedb_cursor cursor
	for select name, status2 from #sysdb
 
	open offlinedb_cursor

	while (@row_count > 0)
	begin
		fetch offlinedb_cursor into @name, @status2
		
		if (@status2 & 16 != 0)
		begin
			/* 18174, "The database '%1!' is offline. To obtain 
			** cache-bindings for objects in this database, 
			** please online the database and rerun sp_helpcache. 
			*/
			exec sp_getmessage 18174, @print_str output
			print @print_str, @name
		end
		select @row_count = @row_count - 1
	end

	close offlinedb_cursor
	return 0
end
else
begin

	/*
	**  If we get here parm1 must be of the form %d[M P K G].
	*/
	exec @stat = sp_aux_getsize @parm1, @size output
	if @stat = 0
	begin
		return 1
	end

	select @overhead = config_admin(12, 0, @size, 0, NULL, NULL)
	select @overhead_sz_str = str(convert(float,@overhead) / 1024, 7, 2) + "Mb"

	select @print_str = convert(varchar(15), @overhead_sz_str) + " of overhead memory will be needed to manage a cache of size " + @parm1

	print @print_str
end

return 0
go
exec sp_procxmode 'sp_helpcache', 'anymode'
go
grant execute on sp_helpcache to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_displaylevel')
begin
	drop procedure sp_displaylevel
end
go
print "Installing sp_displaylevel"
go

/* Stored procedure for assigning config display level for a user login.
**
*/

/*
** Messages for "sp_displaylevel"
**
**  17260, "Can't run %1! from within a transaction."
**  18150, "The login '%s' does not exist."
**  18151, "The current display level for login '%s' is '%s'."
**  18152, "Invalid display level. The valid values are '1', '5' or '10'."
**  18153, "The display level for login '%s' has been changed to '%s'."
*/

create procedure sp_displaylevel
@loginame	varchar(30) = NULL,	/* login name */
@level		varchar(30) = NULL	/* config display level */
as

declare @userid		int
declare @username	varchar(30)
declare @cur_level_int	int
declare @cur_level_char	varchar(20)
declare @msg 		varchar(250)

select @userid = NULL
select @cur_level_int = NULL

/*
** set the user login name
*/
if (@loginame = NULL)
	select @loginame = suser_name()

/*
** set the user id
*/
select @userid = suser_id(@loginame)

/*
** check for invalid @loginame
*/
if (@userid = NULL)
begin
	exec sp_getmessage 18150, @msg output
	print @msg, @loginame
	return(1)
end

/*
** if @level are NULL, just display the user config level
*/
if (@level = NULL)
begin
	/*
	** retrieve the user config level from sysattributes
	*/
	select @cur_level_int = int_value from master.dbo.sysattributes where
		class = 4 and
		attribute = 0 and
		object_type = 'L' and
		object = @userid

	if (@cur_level_int = 10)
		select @cur_level_char = "comprehensive"
	else if (@cur_level_int = 5)
		select @cur_level_char = "intermediate"
	else if (@cur_level_int = 1)
		select @cur_level_char = "basic"
	else
		select @cur_level_char = "comprehensive"

	exec sp_getmessage 18151, @msg output
	print @msg, @loginame, @cur_level_char

	return(0)
end

/*
** check if user has permission to change the display level
** only the user himself or user has sa role can has the permission
*/
select @username = suser_name()
if (@loginame != @username)
begin
	/* check if user has sa role, proc_role will also do auditing
	** if required. proc_role will also print error message if required.
	*/
	if (proc_role("sa_role") = 0)
		return (1)
end

/*
** check if the @level is valid
** the current valid value is 'basic', 'intermediate', and 'comprehensive'.
*/
if (@level = "basic")
	select @cur_level_int = 1
else if (@level = "intermediate")
	select @cur_level_int = 5
else if (@level = "comprehensive")
	select @cur_level_int = 10
else
begin
	exec sp_getmessage 18152, @msg output
	print @msg
	return(1)
end

/*
** Figure out if we need to insert or update from sysattributes. 
*/
if exists (select * from master.dbo.sysattributes where
	class = 4 and
	attribute = 0 and
	object_type = 'L' and
	object = @userid)
begin
	update master.dbo.sysattributes
		set 	int_value = @cur_level_int
		where	class = 4 and
			attribute = 0 and
			object_type = 'L' and
			object = @userid
end
else
begin
	insert into master.dbo.sysattributes 
		(class, attribute, object_type, object, int_value)
		VALUES
		(4,
		 0,
		 'L',
		 @userid,
		 @cur_level_int)
end

exec sp_getmessage 18153, @msg output
print @msg, @loginame, @level

return(0)

go
go
exec sp_procxmode 'sp_displaylevel', 'anymode'
go
grant execute on sp_displaylevel to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_setpglockpromote')
begin
	drop procedure sp_setpglockpromote
end
go
print "Installing sp_setpglockpromote"
go

/* Stored procedure for adding or modifying lock promotion attribute. 
** Database attributes can only be modified when using Master.
*/

/*
** Messages for "sp_setpglockpromote"
**
** 17260, "Can't run %1! from within a transaction."
** 17421, "No such database -- run sp_helpdb to list databases."
** 17460, "Object must be in the current database."
** 18090, "The target object does not exist."
** 18158, "At least one of the parameters 'new_lwm', 'new_hwm' or 'new_pct' must be non-NULL to execute sp_setpglockpromote."
** 18159, "You must be in the 'master' database to add, change or drop lock promotion attribute for a user database."
** 18160, "Please specify a non-NULL value for %1, since it has not been set previously with a non-NULL value."
** 18161, "Object name parameter must be NULL for Server-wide lock promotion attributes. Using NULL instead of - %1."
** 18162, "'%1!' is a not a user table.  '%1' can be used only on user tables."
** 18163, "The 'lock promotion LWM' value %1 cannot be greater than the 'lock promotion HWM' value %2."
** 18164, "Invalid value specified for 'scope' parameter. Valid values are 'SERVER','DATABASE' or 'TABLE'."
** 18165, "The 'lock promotion!' attributes of %1 '%2' have been changed. The new values are %3."
*/

create procedure sp_setpglockpromote
@scope varchar(10),			/* table, database or server */
@objname varchar(92) = NULL,		/* table or database name */
@new_lwm int = NULL,			/* Lock promotion lwm value */
@new_hwm int = NULL,			/* Lock promotion hwm value */
@new_pct int = NULL			/* Lock promotion pct value */
as

declare @attrib_objid int		/* object id of the table/db */
declare @object_type varchar(2)		/* object type of the table/db */
declare @attrib int			/* attrib type of the optname */
declare @use_char_value varchar(42)	/* Lock promotion attribute's char_value */
declare @msg varchar(250)		/* message buffer */
declare @action	int			/* ADD or CHANGE attribute */
declare @ret int 			/* Return value */
declare @tab_type smallint		/* User table ? */
declare @use_lwm int
declare @use_hwm int
declare @use_pct int
declare @update_lwm int
declare @update_hwm int


/* If we're in a transaction, disallow this */
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_setpglockpromote"
        return (1)
end
else
begin
        set chained off
end

set transaction isolation level 1

if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
begin
        /*
        ** 17460, "Object must be in the current database."
        */
        exec sp_getmessage 17460, @msg output
        print @msg
        return (1)
end

if (upper(@scope) != "DATABASE" and upper(@scope) != "SERVER"
   and upper(@scope) != "TABLE")
begin
	/*
	** 18164, "Invalid value specified for 'scope' parameter 
	** Valid values are 'SERVER','DATBASE' or 'TABLE'."
	*/
	exec sp_getmessage 18164, @msg output
	print @msg, @objname
end

if (@new_lwm is NULL and @new_hwm is NULL and @new_pct is NULL)
begin
	/*
	** 18158, "At least one of the parameters 'new_lwm', 'new_hwm' or 
	** 'new_pct' must be non-NULL to execute sp_setpglockpromote."
	*/
	exec sp_getmessage 18158, @msg output
	print @msg
	return 1
end
else
        select @attrib = 0

if (upper(@scope) = "SERVER")
begin
	if @objname is not NULL
	begin
		/*
		** 18161, "Object name parameter must be NULL for Server-wide 
		** lock promotion attributes. Using NULL instead of - %1."
		*/
		exec sp_getmessage 18161, @msg output
		print @msg, @objname
	end

	/*
	** For valid attributes we call sp_configure to set the server-wide
	** values. All 3 server-wide values cannot be set in the same tran,
	** since sp_configure cannot be invoked from within a tran.
	*/
	select @use_lwm = value from master.dbo.sysconfigures
		where config=253

	select @use_hwm = value from master.dbo.sysconfigures
		where config=144

	/* If the new_lwm is NULL, then we're not updating the LWM. */
	if @new_lwm is NULL
	begin
		select @new_lwm = @use_lwm
		select @update_lwm = 0
	end
	else
		select @update_lwm = 1

	/* If the new_hwm is NULL, then we're not updating the HWM. */
	if @new_hwm is NULL
	begin
		select @new_hwm = @use_hwm
		select @update_hwm = 0
	end
	else
		select @update_hwm = 1

	/* Validate that LWM is less than or equal to HWM. */
	if @new_lwm > @new_hwm
	begin
		/*
		** 18163, "The 'lock promotion LWM' value %1 cannot 
		** be greater than the 'lock promotion HWM' value %2."
		**
		*/
		exec sp_getmessage 18163, @msg output
		print @msg, @new_lwm, @new_hwm
		return 1
	end

	/* If the the new LWM value is greater than the existing HWM,
	** then configure the HWM value first so that we dont break
	** the validation criterion.
	*/
	if @new_lwm > @use_hwm
	begin
		if @update_hwm = 1
		begin
			exec @ret = sp_configure "lock promotion HWM", @new_hwm
			if (@ret != 0)
				return @ret
		end

		if @update_lwm = 1
		begin
			exec @ret = sp_configure "lock promotion LWM", @new_lwm
			if (@ret != 0)
				return @ret
		end
	end
	else /* @new_lwm <= @use_hwm */
	begin
		if @update_lwm = 1
		begin
			exec @ret = sp_configure "lock promotion LWM", @new_lwm
			if (@ret != 0)
				return @ret
		end

		if @update_hwm = 1
		begin
			exec @ret = sp_configure "lock promotion HWM", @new_hwm
			if (@ret != 0)
				return @ret
		end
	end

	if (@new_pct is not NULL)
	begin
		exec @ret = sp_configure "lock promotion PCT", @new_pct
		if (@ret != 0)
			return @ret
	end
	/* The server wide values have been successfully configured. */
	return(0)
end

/*
**  Only Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/

if (proc_role("sa_role") != 1)
begin
	/* "User must be System Administrator (SA) 
	** to configure lock promotion attributes. 
	*/
	return(1)
end


if (upper(@scope) = "DATABASE")
begin
	/* 
	** If we're configuring lock promotion for a database, 
	** make sure we're currently in master. 
	*/

	select @attrib_objid = db_id()
	if @attrib_objid != 1
	begin
		/*
		** 18159, "You must be in the 'master' database to add, change 
		** or drop lock promotion attribute for a user database."
		*/
		exec sp_getmessage 18159, @msg output
		print @msg
		return 1
	
	end

	/* Translate dbname to dbid. */
	select @attrib_objid = 0
	select @attrib_objid = dbid from master.dbo.sysdatabases 
			where name = @objname

	if @attrib_objid = 0
	begin
		/*
		** 17421, "No such database -- run sp_helpdb to list databases."
		*/
		exec sp_getmessage 17421, @msg output
		print @msg
		return 1
	end


	select @object_type = 'D'
end

if (upper(@scope) = "TABLE")
begin
	/* Translate objname to objid. */
	select @attrib_objid = 0
	select @attrib_objid = id , @tab_type = sysstat & 7
		from sysobjects where id = object_id(@objname)

	if @attrib_objid = 0
	begin
		/* 
		** 18090, "The target object does not exist."
		*/
                exec sp_getmessage 18090, @msg output
                print @msg
                return 1
	
	end

	if @tab_type != 3
	begin
		/*
		** 18162, "'%1!' is a not a user table. '%2' can be 
		** used only on user tables."
		*/
		exec sp_getmessage 18162, @msg output
		print @msg, @objname, "sp_setpglockpromote"
		return(1)
	end

	select @object_type = 'T'
end

select  @use_lwm = object_info1, @use_hwm = object_info2, 
	@use_pct = object_info3
		 from sysattributes where class =5
		 and  attribute = 0
		 and  object_type = @object_type
		 and  object = @attrib_objid
if @@rowcount != 0
	select @action = 2      /* ATTR_CHANGE */
else
	select @action = 1      /* ATTR_ADD */


/*
** Validate that if a new attribute value is not specified, then an old one 
** exists for each of LWM, HWM and PCT.
*/

if @new_lwm is not NULL
	select @use_lwm = @new_lwm
if @use_lwm is NULL
begin
	/*
	** 18160, "Please specify a non-NULL value for %1, 
	** since it has not been set previously with a non-NULL value."
	*/
	exec sp_getmessage 18160, @msg output
	print @msg, "new_lwm"
	return 1
end

if @new_hwm is not NULL
	select @use_hwm = @new_hwm
if @use_hwm is NULL
begin
	/*
	** 18160, "Please specify a non-NULL value for %1, 
	** since it has not been set previously with a non-NULL value."
	*/
	exec sp_getmessage 18160, @msg output
	print @msg, "new_hwm"
	return 1
end

if @new_pct is not NULL
	select @use_pct = @new_pct
if @use_pct is NULL
begin
	/*
	** 18160, "Please specify a non-NULL value for %1, 
	** since it has not been set previously with a non-NULL value."
	*/
	exec sp_getmessage 18160, @msg output
	print @msg, "new_pct"
	return 1
end

/* Validate that LWM is less than or equal to HWM. */

if @use_lwm > @use_hwm
begin
	/*
	** 18163, "The 'lock promotion LWM' value %1 cannot 
	** be greater than the 'lock promotion HWM' value %2."
	**
	*/
	exec sp_getmessage 18163, @msg output
	print @msg, @use_lwm, @use_hwm
	return 1
end

/*
** Assemble the char_value field for sysattributes. This is needed for
** sp_help and sp_helpdb to display all 3 of LWM, HWM and PCT, even though
** we use an umbrella attribute "lock promote".
*/

select @use_char_value = "PCT = "+ convert(varchar(3),@use_pct) + 
			", LWM = "+ convert(varchar(10),@use_lwm) + 
			", HWM = " + convert(varchar(10),@use_hwm)

begin transaction

	/* Validate boundary conditions for the attributes. */
	select @ret = attrib_valid(5, @attrib, @object_type,
			@attrib_objid, @use_lwm, @use_hwm, @use_pct, NULL,
			NULL, NULL, NULL, NULL, NULL, @action)

	if @ret = 0	/* Validation routine returned false. */
	begin
		rollback tran
		return (1)
	end

	if (@action = 2)	/* ATTR_CHANGE */
	begin
		update sysattributes 
			set char_value = @use_char_value,
			    object_info1 = @use_lwm,
			    object_info2 = @use_hwm, 
			    object_info3 = @use_pct
			where class =5
				 and  attribute = @attrib
				 and  object_type = @object_type
				 and  object = @attrib_objid

		/*
		** If there was an error, @@error will be non-zero
		*/
		if @@error != 0
		begin
			if @@trancount != 0
				rollback transaction
			return (1)
		end
	end
	else			/* ADD attribute */
	begin

		insert into sysattributes(class, attribute, object_type, object,
					 object_info1, object_info2, 
					 object_info3, char_value)
			values(5, @attrib, @object_type, @attrib_objid, 
						@new_lwm, @new_hwm, @new_pct,
							@use_char_value)

		/*
		** If there was an error, @@error will be non-zero
		*/
		if @@error != 0
		begin
			if @@trancount != 0
				rollback transaction
			return (1)
		end
	end

					
/* Notify */
select @ret = attrib_notify(5, @attrib, @object_type,
		@attrib_objid, @use_lwm, @use_hwm, @use_pct, NULL,
		NULL, NULL, NULL, NULL, NULL, @action)

if @ret = 0	/* Unable to notify ? */
begin
	rollback tran
	return (1)
end
		
commit transaction

/*
** 18165, "The 'lock promotion!' attributes of %1, '%2' 
** have been changed. The new values are %3."
*/
exec sp_getmessage 18165, @msg output
print @msg, @scope, @objname, @use_char_value

return (0)
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dropglockpromote')
begin
	drop procedure sp_dropglockpromote
end
go
print "Installing sp_dropglockpromote"
go

/* Stored procedure for dropping lock promotion attributes. 
** Database attributes can only be modified when using Master.
*/

/*
** Messages for "sp_dropglockpromote"
**
** 17260, "Can't run %1! from within a transaction."
** 17421, "No such database -- run sp_helpdb to list databases."
** 17460, "Object must be in the current database."
** 18090, "The target object does not exist."
** 18159, "You must be in the 'master' database to add, change or drop lock promotion attribute for a user database."
** 18162, "'%1!' is a not a user table. '%2' can be used only on user tables."
** 18166, "Lock promotion attribute does not exist for %1, '%2'. Cannot delete it."
** 18167, "Lock promotion attribute of object '%1!' has been dropped!."
** 18168, "Invalid value '%1', specified for 'scope' parameter. Valid values are 'DATABASE' or 'TABLE'."
** 18169, "Server-wide lock promotion values cannot be dropped. Use 'sp_configure' to restore server-wide defaults.
*/

create procedure sp_dropglockpromote
@scope varchar(10),			/* table, database or server */
@objname varchar(92) = NULL		/* table or database name */
as

declare @attrib_objid int		/* object id of the table/db */
declare @object_type varchar(2)		/* object type of the table/db */
declare @attrib int			/* attrib type of the optname */
declare @msg varchar(250)		/* message buffer */
declare @action	int			/* DROP sysattributes row */
declare @ret int 			/* Return value of built-in: attrib_notify. */
declare @tab_type smallint		/* User table ? */


if (upper(@scope) = "SERVER")
begin
        /*
        ** 18169, "Server-wide lock promotion values cannot be dropped.
        ** Use 'sp_configure' to restore server-wide defaults.
        */
        exec sp_getmessage 18169, @msg output
        print @msg
end

if (upper(@scope) != "DATABASE" and upper(@scope) != "TABLE")
begin
        /*
        ** 18168, "Invalid value '%1', specified for 'scope' parameter
        ** Valid values are 'DATABASE' or 'TABLE'."
        */
        exec sp_getmessage 18168, @msg output
        print @msg, @scope
end

/* If we're in a transaction, disallow this */
if @@trancount > 0
begin
        /*
        ** 17260, "Can't run %1! from within a transaction."
        */
        exec sp_getmessage 17260, @msg output
        print @msg, "sp_dropglockpromote"
        return (1)
end
else
begin
        set chained off
end

set transaction isolation level 1

/*
**  Make sure the @objname is local to the current database.
*/
if @objname like "%.%.%" and
	substring(@objname, 1, charindex(".", @objname) - 1) != db_name()
begin
        /*
        ** 17460, "Object must be in the current database."
        */
	exec sp_getmessage 17460, @msg output
        print @msg
        return (1)
end

/*
**  Only Accounts with SA role can execute it.
**  Call proc_role() with the required SA role.
*/

if (proc_role("sa_role") != 1)
begin
	/* "User must be System Administrator (SA) 
	** to configure lock promotion attributes. 
	*/
	return(1)
end

if (upper(@scope) = "DATABASE")
begin
	/* If we're dropping lock promotion for a database, 
	**	make sure we're currently in master. */

	select @attrib_objid = db_id()
	if @attrib_objid != 1
	begin
		/*
		** 18159, "You must be in the 'master' database to add, change 
		** or drop lock promotion attribute for a user database."
		*/
		exec sp_getmessage 18159, @msg output
		print @msg
		return 1
	
	end

	/* Translate dbname to dbid. */
	select @attrib_objid = 0
	select @attrib_objid = dbid from master.dbo.sysdatabases 
			where name = @objname

	if @attrib_objid = 0
	begin
		/*
		** 17421, "No such database -- run sp_helpdb to list databases."
		*/
		exec sp_getmessage 17421, @msg output
		print @msg
		return 1
	end


	select @object_type = 'D'
end

if (upper(@scope) = "TABLE")
begin
	/* Translate objname to objid. */
	select @attrib_objid = 0
	select @attrib_objid = id , @tab_type = sysstat & 7
		from sysobjects where id = object_id(@objname)

	if @attrib_objid = 0
	begin
		/* 
		** 18090, "The target object does not exist."
		*/
                exec sp_getmessage 18090, @msg output
                print @msg
                return 1
	
	end

	if @tab_type != 3
	begin
		/*
		** 18162, "'%1!' is a not a user table. '%2'
		**  can be used only on user tables."
		*/
		exec sp_getmessage 18162, @msg output
		print @msg, @objname, "sp_dropglockpromote"
		return
	end

	select @object_type = 'T'
end

select @action = 3      /* ATTR_DROP */
select @attrib = 0	/* lock promotion attribute */

if not exists(select * from sysattributes where class =5
			 and  attribute = 0
			 and  object_type = @object_type
			 and  object = @attrib_objid)
begin
		/*
                ** 18166, "Lock promotion attribute does not exist for
                ** %1,'%2' . Cannot delete it!"
                */
                exec sp_getmessage 18166, @msg output
                print @msg, @scope, @objname
                if @@trancount != 0
                        rollback transaction
                return (1)
end

begin transaction

delete from sysattributes 
	where class =5
	 and  attribute = @attrib
	 and  object_type = @object_type
	 and  object = @attrib_objid

/*
** If there was an error, @@error will be non-zero
*/
if @@error != 0
begin
	if @@trancount != 0
		rollback transaction
	return (1)
end
					
/* Notify */
select @ret = attrib_notify(5, @attrib, @object_type,
		@attrib_objid, NULL, NULL, NULL, NULL,
		NULL, NULL, NULL, NULL, NULL, @action)

if @ret = 0	/* Unable to notify ? */
begin
	rollback tran
	return (1)
end
		
commit transaction

begin
	/*
	** 18167, "Lock promotion attribute of object '%1!' has been dropped!."
	*/
	exec sp_getmessage 18167, @msg output
	print @msg,@objname
end

return (0)
go
exec sp_procxmode 'sp_dropglockpromote', 'anymode'
go
grant execute on sp_dropglockpromote to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_kernel')
begin
	drop procedure sp_sysmon_kernel
end
go
print "Installing sp_sysmon_kernel"
go

/* This stored procedure produces a report containing a summary of
** SQL Server engine activity.
*/
create procedure sp_sysmon_kernel
	@NumEngines tinyint,	/* number of engines online */
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */

as

/* --------- declare local variables --------- */
declare @i smallint		/* loop index to iterate through  multi-group
				** counters (engine, disk, & buffer) */
declare @tmp_grp varchar(25)	/* temp var to build group_names
				** ie. engine_N, disk_N */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @tmp_percent real	/* temp var for percentage storage */
declare @tmp_sum_percent real	/* temp var for summing percentage info */
declare @avg1line char(67)	/* string to delimit avg lines on printout */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @sum2line char(67)	/* string to delimit total lines with percent 
				** calc on printout */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted statistics line for print 
				** statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @avg1line   = "  -----------             ---------------          ----------------"
select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @sum2line   = "  -------------------------  ------------  ------------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"


/* ======================= Kernel Utilization Section =================== */
print @blankline
print "Kernel Utilization"
print "------------------"
print @blankline
print "  Engine Busy Utilization:"

select @i = 0, @tmp_sum_percent = 0

while @i < @NumEngines                                   /* for each engine */
  begin
	/* build group_name string */
	select @tmp_grp = "engine_" + convert(varchar(2), @i) 

	select @tmp_percent = 100.0 * ((convert(real,a.value) - b.value)
					/ a.value)
	  from #tempmonitors a, #tempmonitors b
	  where a.group_name = @tmp_grp and
      		a.group_name = b.group_name and
			a.field_name = "clock_ticks" and
			b.field_name = "idle_ticks"  

	select @tmp_sum_percent = @tmp_sum_percent + @tmp_percent

	select @rptline = "    Engine " + convert(char(2), @i) + space(21) +
					str(@tmp_percent,5,1) + @psign
	print @rptline

	select @i = @i + 1
  end

if @NumEngines > 1
  begin
	print @avg1line
	select @rptline = "  Summary:" + space(16) +
					"Total:" + str(@tmp_sum_percent,7,1) +
						 @psign + space(10) +
					"Average: " + str(@tmp_sum_percent / 
						@NumEngines,5,1) + @psign
	print @rptline
  end

print @blankline
print @blankline
print "  CPU Yields by Engine            per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
        field_name = "engine_sleeps"

if @tmp_total = 0	/* Avoid divide by zero errors - just print zero's */
  print @zero_str

else
  begin
	select @i = 0
	while @i < @NumEngines		/* for each engine */
	  begin
		/* build group_name string */
		select @tmp_grp= "engine_" + convert(varchar(2), @i) 
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "engine_sleeps"

		select @rptline = "    Engine " + convert(char(2),@i) + 
					space(16) +
					str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) 
					+ space(2) +
					str(@tmp_int / convert(real, @NumXacts),12,1) 
					+ space(2) +
					str(@tmp_int, 10) + space(5) +
					str(100.0 * @tmp_int / @tmp_total,5,1) 
					+ @psign
		print @rptline
		select @i = @i + 1
	  end

	if @NumEngines > 1
	  begin
		print @sum2line 
		select @rptline = "  Total CPU Yields:" + space(10) +
					str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) 
					+ space(2) +
					str(@tmp_total / convert(real,@NumXacts),12,1) 
					+ space(2) +
					convert(char(10), @tmp_total)
		print @rptline
	  end
  end
print @blankline
print @blankline

print "  Network Checks"

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name = "kernel" and
  field_name like "ncheck_%"

if @tmp_total = 0	/* Avoid divide by zero errors - print zero's */
  print @zero_str

else              
  begin
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "kernel" and
	  		field_name = "ncheck_nonblocking"
	  
	select @rptline = "    Non-Blocking" + space(13) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1)
				+ @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "kernel" and
	  		field_name = "ncheck_blocking"

	select @rptline = "    Blocking" + space(17) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	print @sum2line 
	select @rptline = "  Total Network I/O Checks:" + space(2) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real,@NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10)
	print @rptline

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "network" and
			field_name like "total_packets_%"

	select @rptline = "  Avg Net I/Os per Check" + space(14) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(convert(real, @tmp_int) / @tmp_total,10,5)+
				space(7) +
				@na_str
	print @rptline
  end
print @blankline
print @blankline

print "  Disk I/O Checks"

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "dcheck_calls"

if @tmp_total = 0	/* Avoid divide by zero errors - print zero's */
  print @zero_str

else              
  begin
	select @rptline = "    Total Disk I/O Checks" + space(4) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
	print @rptline

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "engine_%" and
			field_name = "dchecks_calling_dpoll"

	select @rptline = "    Checks Returning I/O" + space(5) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
 				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int/ @tmp_total,5,1) + @psign
	print @rptline

	/* save checks returning i/o value for average calc below */
	select @tmp_total = @tmp_int

	if @tmp_total != 0
	  begin
		select @tmp_int = SUM(value)
		  from #tempmonitors
		  where group_name like "engine_%" and
				field_name = "total_dpoll_completed_aios"

		select @rptline = "    Avg Disk I/Os Returned" + space(12) +
						@na_str + space(11) +
						@na_str + space(2) +
						str(convert(real, @tmp_int) / 
							@tmp_total,10,5) + 
						space(7) +
						@na_str
		print @rptline
	  end
  end

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_kernel', 'anymode'
go
grant execute on sp_sysmon_kernel to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_xactsum')
begin
	drop procedure sp_sysmon_xactsum
end
go
print "Installing sp_sysmon_xactsum"
go

/* This stored procedure produces a report containing a summary of
** the type of activites performed by transactions running during
** the sampling period, including the number of transactions and 
** a summary of insert, update and delete activity.
**
*/
create procedure sp_sysmon_xactsum
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @NumXactOps int		/* total # of rows affected by 
				** inserts/updates/deletes */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_int2 int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @sum2line char(67)	/* string to delimit total lines with percent 
				** calc on printout */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @sum2line   = "  -------------------------  ------------  ------------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

/* ================ Transaction Profile Section ================= */
print @blankline
print "Transaction Profile"
print "-------------------"
print @blankline

/* -------- transaction summary ------------*/
print "  Transaction Summary             per sec      per xact       count  %% of total"
print @sum1line

select @rptline = "    Committed Xacts" + space(10) +
			str(@NumXacts / (@NumElapsedMs / 1000.0),12,1) + 
			space(11) + @na_str + space(2) +
			str(@NumXacts,10) + space(5) +	@na_str
print @rptline
print @blankline
print @blankline
  
/*
** transaction detail
*/

print "  Transaction Detail              per sec      per xact       count  %% of total"
print @sum1line

/* 
**  get total number of Transaction Operations for percentage 
**  calculations on total lines 
*/
select @NumXactOps = SUM(value)
  from #tempmonitors
  where group_name = 'access' and field_name IN	
			("ncinsert", "cinsert","deferred_update",
			 "direct_inplace_update","direct_notinplace_update",
			 "direct_expensive_update","delete")

if @NumXactOps = 0			/* Avoid Divide by Zero Errors */
  print @zero_str

else              
  begin
	print "    Inserts"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = 'access' and
			field_name IN ("ncinsert", "cinsert")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
	  print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = 'access' and
				field_name = "ncinsert"

		select @rptline = "      Heap Table" + space(13) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = 'access' and
				field_name = "cinsert"

		select @rptline = "      Clustered Table" + space(8) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

	  end		/* else */ 

	print @sum2line 
	select @rptline = "    Total Rows Inserted" + space(6) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @NumXactOps,5,1) + @psign
	print @rptline
	print @blankline

	print "    Updates"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = 'access' and field_name IN 
		("deferred_update","direct_inplace_update",
		 "direct_notinplace_update","direct_expensive_update")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
	  print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = 'access' and
				field_name = "deferred_update"

		select @rptline = "      Deferred" + space(15) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = 'access' and
				field_name = "direct_inplace_update"

		select @rptline = "      Direct In-place" + space(8) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) +space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = 'access' and
				field_name = "direct_notinplace_update"

		select @rptline = "      Direct Cheap" + space(11) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = 'access' and
				field_name = "direct_expensive_update"

		select @rptline = "      Direct Expensive" + space(7) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

	  end

	print @sum2line 
	select @rptline = "    Total Rows Updated" + space(7) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @NumXactOps,5,1) + @psign
	print @rptline
	print @blankline

	print "    Deletes"

	select @tmp_total = value
	  from #tempmonitors
	  where group_name = 'access' and
			field_name = "delete"

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
	  print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = 'access' and
				field_name = "delete_deferred"

		select @rptline = "      Deferred" + space(15) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		/* Calc Direct Deletes as access.delete - access.delete_deferred */
		select @tmp_int2 = @tmp_total - @tmp_int

		select @rptline = "      Direct" + space(17) +
			str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int2 / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int2, 10) + space(5) +
			str(100.0 * @tmp_int2 / @tmp_total,5,1) + @psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "    Total Rows Deleted" + space(7) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @NumXactOps,5,1) + @psign
	print @rptline
  end		/* else @NumXactOps != 0 */

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_xactsum', 'anymode'
go
grant execute on sp_sysmon_xactsum to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_xactmgmt')
begin
	drop procedure sp_sysmon_xactmgmt
end
go
print "Installing sp_sysmon_xactmgmt"
go

/* This stored procedure produces a report containing a summary of
** log activity including activity in the user log caches.
*/
create procedure sp_sysmon_xactmgmt

	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_int2 int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @sum2line char(67)	/* string to delimit total lines with 
				** percent calc on printout */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on					/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @sum2line   = "  -------------------------  ------------  ------------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

print @blankline

print "Transaction Management"
print "----------------------"
print @blankline
print "  ULC Flushes to Xact Log         per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name = 'xls' and
		field_name like "plc_flush_%"

if @tmp_total = 0			/* Avoid Divide by Zero Errors */
  print @zero_str

else              
  begin
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = 'xls' and
			field_name = "plc_flush_full"

	select @rptline = "    by Full ULC" + space(14) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = 'xls' and
			field_name = "plc_flush_endxact"

	select @rptline = "    by End Transaction" + space(7) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = 'xls' and
			field_name = "plc_flush_xdeschange"

	select @rptline = "    by Change of Database" + space(4) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = 'xls' and
			field_name = "plc_flush_slr_xact"

	select @rptline = "    by System Log Record" + space(5) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = 'xls' and field_name IN 
		("plc_flush_unpin","plc_flush_discard","plc_flush_pmscan")

	select @rptline = "    by Other" + space(17) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	print @sum2line 
	select @rptline = "  Total ULC Flushes" + space(10) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10)
	print @rptline
  end

print @blankline
print @blankline

select @tmp_int = value
  from #tempmonitors
  where group_name = 'xls' and
		field_name = "plc_logrecs"

select @rptline = "  ULC Log Records" + space(12) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

select @tmp_int = value
  from #tempmonitors
  where group_name = 'xls' and
		field_name = "plc_maxused"

select @rptline = "  Max ULC Size" + space(24) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(@tmp_int, 10) + space(7) +
				@na_str
print @rptline
print @blankline
print @blankline

print "  ULC Semaphore Requests"

select @tmp_total = value
  from #tempmonitors
  where group_name = 'xls' and
		field_name = "plc_lock_calls"

if @tmp_total = 0			/* Avoid Divide by Zero Errors */
  print @zero_str

else              
  begin
	select @tmp_int2 = value
	  from #tempmonitors
	  where group_name = 'xls' and
			field_name = "plc_lock_waits"

	/* calculate "immediately granted" spinlocks */
	select @tmp_int = @tmp_total - @tmp_int2


	select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int/convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	select @rptline = "    Waited" + space(19) +
			str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int2 / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int2, 10) + space(5) +
			str(100.0 * @tmp_int2 / @tmp_total,5,1) + 
			@psign
	print @rptline

	print @sum2line 
	select @rptline = "  Total ULC Semaphore Req" + space(4) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10)


	print @rptline
  end	/* else @tmp_total != 0 */

print @blankline
print @blankline

print "  Log Semaphore Requests"

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name = 'xls' and
		field_name IN ("log_lock_granted", "log_lock_waited")

if @tmp_total = 0			/* Avoid Divide by Zero Errors */
  print @zero_str

else              
  begin
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = 'xls' and
			field_name = "log_lock_granted"

	select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = 'xls' and
			field_name = "log_lock_waited"

	select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	print @sum2line 
	select @rptline = "  Total Log Semaphore Req" + space(4) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10)
	print @rptline
  end

print @blankline
print @blankline

select @tmp_int = SUM(value)
  from #tempmonitors
  where group_name like "buffer_%" and
		field_name = "log_page_writes"

select @rptline = "  Transaction Log Writes" + space(5) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

select @tmp_int2 = value
  from #tempmonitors
  where group_name = "access" and
		field_name = "log_page_allocations"         

select @rptline = "  Transaction Log Alloc" + space(6) +
			str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int2 / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int2, 10) + space(7) +
			@na_str
print @rptline

if @tmp_int2 != 0	/* avoid divide by zero errors */
  begin
	select @rptline = "  Avg # Writes per Log Page" + space(11) +
					@na_str + space(11) +
					@na_str + space(2) + 
					str(convert(real, @tmp_int) / @tmp_int2, 10,5) + space(7) +
					@na_str
	print @rptline
  end

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_xactmgmt', 'anymode'
go
grant execute on sp_sysmon_xactmgmt to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_index')
begin
	drop procedure sp_sysmon_index
end
go
print "Installing sp_sysmon_index"
go

/* This stored procedure produces a report containing a summary of
** index behavior including deadlocks and page splits.
*/
create procedure sp_sysmon_index
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

print @blankline

print "Index Management"
print "----------------"
print @blankline

print "  Nonclustered Maintenance        per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = value
  from #tempmonitors
  where group_name = 'access' and
		field_name = "ncupdate"

select @rptline = "    Ins/Upd Requiring Maint" + space(2) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

select @tmp_int = value
  from #tempmonitors
  where group_name = 'access' and
		field_name = "ncupdate_indexes"

select @rptline = "      # of NC Ndx Maint" + space(6) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0
  begin
	select @rptline = "      Avg NC Ndx Maint / Op" + space(11) +
			@na_str + space(11) +
			@na_str +space(2) +
			str(convert(real, @tmp_int) / @tmp_total, 10,5) + 
			space(7) +
			@na_str
	print @rptline
  end

print @blankline

select @tmp_total = value
  from #tempmonitors where
  group_name = 'access' and
  field_name = "ncdelete"

select @rptline = "    Deletes Requiring Maint" + space(2) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

select @tmp_int = value
  from #tempmonitors
  where group_name = 'access' and
		field_name = "ncdelete_indexes"

select @rptline = "      # of NC Ndx Maint" + space(6) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0
  begin
	select @rptline = "      Avg NC Ndx Maint / Op" + space(11) +
			@na_str + space(11) +
			@na_str +space(2) +
			str(convert(real, @tmp_int) / @tmp_total, 10,5) + 
			space(7) +
			@na_str
	print @rptline
  end

print @blankline

select @tmp_total = value
  from #tempmonitors
  where group_name = 'access' and
		field_name = "ncrid_update"

select @rptline = "    RID Upd from Clust Split " +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

select @tmp_int = value
  from #tempmonitors
  where group_name = 'access' and
		field_name = "ncrid_update_indexes"

select @rptline = "      # of NC Ndx Maint" + space(6) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0
  begin
	select @rptline = "      Avg NC Ndx Maint / Op" + space(11) +
			@na_str + space(11) +
			@na_str +space(2) +
			str(convert(real, @tmp_int) / @tmp_total, 10,5) + 
			space(7) +
			@na_str
	print @rptline
  end

print @blankline
print @blankline

select @tmp_total = a.value + b.value
  from #tempmonitors a, #tempmonitors b
  where a.group_name = "access" and
		b.group_name = a.group_name and
		a.field_name = "split_index" and
		b.field_name="split_root"

select @rptline = "  Page Splits" + space(16) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0			/* Avoid Divide by Zero Errors */
  begin
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "access" and
			field_name = "split_index_retry"

	select @rptline = "    Retries" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "access" and
			field_name = "split_index_deadlock"

	select @rptline = "    Deadlocks" + space(16) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @rptline = "    Empty Page Flushes" + space(7) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "access" and
			field_name = "add_ind_level"

	select @rptline = "    Add Index Level" + space(10) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

  end

print @blankline
print @blankline

select @tmp_int = SUM(value)
  from #tempmonitors
  where group_name = "access" and
		field_name like "shrink%"

select @rptline = "  Page Shrinks" + space(15) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_index', 'anymode'
go
grant execute on sp_sysmon_index to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_locks')
begin
	drop procedure sp_sysmon_locks
end
go
print "Installing sp_sysmon_locks"
go

/* This stored procedure produces a report containing a summary of
** of locking characteristics including lock requests and waits.
*/
create procedure sp_sysmon_locks

	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */

declare @TotalLocks int		/* Count Total Number of Locks */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_int2 int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @sum2line char(67)	/* string to delimit total lines with 
				** percent calc on printout */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @sum2line   = "  -------------------------  ------------  ------------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

print @blankline

print "Lock Management"
print "---------------"
print @blankline
print "  Lock Summary                    per sec      per xact       count  %% of total"
print @sum1line

select @TotalLocks = SUM(value)
  from #tempmonitors
  where group_name = "lock" and
		(field_name like "granted%" or field_name like "waited%")

select @rptline = "  Total Lock Requests" + space(8) +
			str(@TotalLocks / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@TotalLocks / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@TotalLocks,10) + space(7) +
			@na_str
print @rptline

if @TotalLocks != 0	/* Avoid Divide by Zero Errors after printout */
  begin
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			field_name like "%waited%"

	select @rptline = "  Avg Lock Contention" + space(8) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @TotalLocks,5,1) + 
				@psign
	print @rptline

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlocks"

	select @rptline = "  Deadlock Percentage" + space(8) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @TotalLocks,5,1) + 
				@psign
	print @rptline
	print @blankline
	print @blankline

	print "  Lock Detail                     per sec      per xact       count  %% of total"
	print @sum1line
	print @blankline

	print "  Exclusive Table"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_EX_TAB" or 
				field_name = "waited_EX_TAB")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_EX_TAB"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_EX_TAB"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline
      end
	print @sum2line 
	select @rptline = "  Total EX-Table Requests" + space(4) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + 
			@psign
	print @rptline
	print @blankline
	print @blankline

	print "  Shared Table"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
	  (field_name = "granted_SH_TAB" or field_name = "waited_SH_TAB")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_SH_TAB"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_SH_TAB"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "  Total SH-Table Requests" + space(4) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + 
			@psign
	print @rptline
	print @blankline
	print @blankline

	print "  Exclusive Intent"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_EX_INT" or 
				field_name = "waited_EX_INT")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_EX_INT"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_EX_INT"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "  Total EX-Intent Requests" + space(3) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + 
			@psign
	print @rptline
	print @blankline
	print @blankline

	print "  Shared Intent"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_SH_INT" or 
				field_name = "waited_SH_INT")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_SH_INT"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_SH_INT"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline
	  end
	print @sum2line 

	select @rptline = "  Total SH-Intent Requests" + space(3) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + 
			@psign
	print @rptline
	print @blankline
	print @blankline

	print "  Exclusive Page"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_EX_PAGE" or 
				field_name = "waited_EX_PAGE")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_EX_PAGE"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_EX_PAGE"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "  Total EX-Page Requests" + space(5) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + @psign
	print @rptline
	print @blankline
	print @blankline

	print "  Update Page"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_UP_PAGE" or 
				field_name = "waited_UP_PAGE")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_UP_PAGE"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_UP_PAGE"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "  Total UP-Page Requests" + space(5) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + @psign
	print @rptline
	print @blankline
	print @blankline

	print "  Shared Page"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_SH_PAGE" or 
				field_name = "waited_SH_PAGE")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_SH_PAGE"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_SH_PAGE"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "  Total SH-Page Requests" + space(5) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + @psign
	print @rptline
	print @blankline
	print @blankline

	print "  Exclusive Address"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_EX_ADDR" or 
				field_name = "waited_EX_ADDR")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_EX_ADDR"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_EX_ADDR"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "  Total EX-Address Requests  " +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real,@NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + @psign
	print @rptline

	print @blankline
	print @blankline

	print "  Shared Address"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			(field_name = "granted_SH_ADDR" or 
				field_name = "waited_SH_ADDR")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "granted_SH_ADDR"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "lock" and
				field_name = "waited_SH_ADDR"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline
	  end

	print @sum2line 
	select @rptline = "  Total SH-Address Requests  " +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real,@NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + @psign
	print @rptline

	print @blankline
	print @blankline

	print "  Last Page Locks on Heaps"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = "access" and
		(field_name = "locklastpage" or field_name = "lklastpg_wait")

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "access" and
				field_name = "locklastpage"

		select @rptline = "    Granted" + space(18) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = "access" and
				field_name = "lklastpg_wait"

		select @rptline = "    Waited" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline
	  end
	print @sum2line 
	select @rptline = "  Total Last Pg Locks"+ space(8) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10) + space(5) +
			str(100.0 * @tmp_total / @TotalLocks,5,1) + @psign
	print @rptline
  end

print @blankline
print @blankline

print "  Deadlocks by Lock Type          per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = value
  from #tempmonitors
  where group_name = "lock" and
		field_name = "deadlocks"

if @tmp_total = 0			/* Avoid Divide by Zero Errors */
	print @zero_str
else
  begin

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_EX_TAB"

		select @rptline = "    Exclusive Table" + space(10) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_SH_TAB"

	select @rptline = "    Shared Table" + space(13) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_EX_INT"

	select @rptline = "    Exclusive Intent" + space(9) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_SH_INT"

	select @rptline = "    Shared Intent" + space(12) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_EX_PAGE"

	select @rptline = "    Exclusive Page" + space(11) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_UP_PAGE"

	select @rptline = "    Update Page" + space(14) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_SH_PAGE"

	select @rptline = "    Shared Page" + space(14) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "address_deadlock"

	select @rptline = "    Address" + space(18) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	print @sum2line 
	select @rptline = "  Total Deadlocks" + space(12) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10)
	print @rptline
  end

print @blankline
print @blankline

select @tmp_int2 = @tmp_total   /* save for deadlock search calc */

print "  Deadlock Detection"

select @tmp_total = value
  from #tempmonitors
  where group_name = "lock" and
		field_name = "deadlock_search"

	select @rptline = "    Deadlock Searches" + space(8) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0			/* Avoid Divide by Zero Errors */
  begin

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "deadlock_alarm_skipped"

	select @rptline = "    Searches Skipped" + space(9) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @rptline = "    Avg Deadlocks per Search" + space(10) +
			@na_str + 
			space(11) +
			@na_str + 
			space(2) +
			str(convert(real,@tmp_int2) / @tmp_total,10,5) + 
			space(7) +
			@na_str
		print @rptline
  end
print @blankline
print @blankline

print "  Lock Promotions"

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name = "lock" and
		field_name like "promoted_%_TAB"

if @tmp_total = 0			/* Avoid Divide by Zero Errors */
	print @zero_str
else
  begin

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "promoted_EX_TAB"

	select @rptline = "    Ex-Page to Ex-Table" + space(6) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "lock" and
			field_name = "promoted_SH_TAB"

	select @rptline = "    Sh-Page to Sh-Table" + space(6) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	print @sum2line 
	select @rptline = "  Total Lock Promotions" + space(6) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10)
	print @rptline
  end

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_locks', 'anymode'
go
grant execute on sp_sysmon_locks to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_dcache')
begin
	drop procedure sp_sysmon_dcache
end
go
print "Installing sp_sysmon_dcache"
go

/* This stored procedure produces a report containing a summary of
** of how user defined caches and buffer pools are being used.
*/
create procedure sp_sysmon_dcache

	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @CacheName varchar(30)	/* Cache Name from cache id lookup */
declare @CacheID smallint	/* Cache ID to map to buffer_N group */
declare @NumCaches smallint	/* Number of Caches to Report On */
declare @TotalSearches int	/* Total Cache Searches on All Caches */
declare @j smallint		/* loop index to iterate through multi-counter 
				** counters (pool...) */
declare @lrgpool tinyint	/* boolean (0=No, 1=yes) logic to print 
				** "Lrg Pool Not Used" Msg
				*/
declare @gt2Kpool tinyint	/* Boolean set while looking for a pool >2K
				** in current cache of size 2, 4, 8, 16 etc.
				** 	0 : Did not find pool
				**	1 : Did find a pool of current size.
				*/
declare @tmp_grp varchar(25)	/* temp var for build group_name's 
				** ie. engine_N, disk_N */
declare @tmp_cntr varchar(35)	/* temp var for build field_name's 
				** ie. bufgrab_Nk */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_int2 int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @subsection char(80)	/* string to delimit subsections on printout */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @sum2line char(67)	/* string to delimit total lines with 
				** percent calc on printout */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @subsection = "-------------------------------------------------------------------------------"
select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @sum2line   = "  -------------------------  ------------  ------------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

print @blankline
print "Data Cache Management"
print "---------------------"
print @blankline
print "  Cache Statistics Summary (All Caches)"
print "  -------------------------------------"
print @blankline
print "    Cache Search Summary"

/*
** get total cache searches on all caches 
*/
select @TotalSearches = SUM(value)	
  from #tempmonitors
  where group_name like "buffer_%" and
		field_name = "bufsearch_calls" 

select @tmp_int = SUM(value)		/* get cache hits on all caches */
  from #tempmonitors
  where group_name like "buffer_%" and
		field_name = "bufsearch_finds"

select @tmp_int2 = @TotalSearches - @tmp_int  /* calc total cache misses */

if @TotalSearches = 0			/* Avoid Divide by Zero Errors */
	print @zero_str
else
  begin

	select @rptline = "      Total Cache Hits" + space(7) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @TotalSearches,5,1) + 
			@psign
	print @rptline

	select @rptline="      Total Cache Misses" + space(5) +
			str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int2 / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int2, 10) + space(5) +
			str(100.0 * @tmp_int2 / @TotalSearches,5,1) + 
			@psign
	print @rptline

	print @sum2line 
	select @rptline = "    Total Cache Searches" + space(5) +
			str(@TotalSearches / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@TotalSearches / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@TotalSearches, 10)
	print @rptline
  end

print @blankline
print @blankline

print "    Cache Turnover"

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "buffer_%" and
		field_name like "bufgrab_%k"

select @rptline = "      Buffers Grabbed" + space(8) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0			/* Avoid Divide by Zero Errors */
  begin

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name like "bufgrab_dirty_%"

	select @rptline = "      Buffers Grabbed Dirty" + space(2) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline
  end
print @blankline
print @blankline

print "    Cache Strategy Summary"

/*
** Sum all buf unkeeps to look at % of buffers following 
** MRU vs Discard Strategy 
*/

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "buffer_%" and
		field_name IN ("bufunkeep_lru", "bufunkeep_mru")

if @tmp_total = 0			/* Avoid Divide by Zero Errors */
	print @zero_str
else
  begin

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name = "bufunkeep_lru"

	select @rptline = "      Cached (LRU) Buffers" + space(3) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name = "bufunkeep_mru"

	select @rptline = "      Discarded (MRU) Buffers" +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline
  end
print @blankline
print @blankline

print "    Large I/O Usage"

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "buffer_%" and
		field_name = "prefetch_req"

if @tmp_total = 0			/* Avoid Divide by Zero Errors */
	print @zero_str
else
  begin

	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and field_name IN
		 ("prefetch_as_requested", "prefetch_page_realigned")

	select @rptline = "      Large I/Os Performed" + space(3) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline

	select @tmp_int2 = @tmp_total - @tmp_int

	select @rptline = "      Large I/Os Denied" + space(6) +
			str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int2 / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int2, 10) + space(5) +
			str(100.0 * @tmp_int2 / @tmp_total,5,1) + 
			@psign
	print @rptline

	print @sum2line 
	select @rptline = "    Total Large I/O Requests " +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10)
	print @rptline
  end

print @blankline
print @blankline

print "    Large I/O Effectiveness"

/*
**  calc total # of 2kb pages brought into all caches from all 
**  large I/Os (non-2kb i/o) 
*/

/*
**  init loop var's to loop through all possible pool sizes (2,4,8,16) 
*/
select @tmp_total = 0, @j = 4

while (@j <= 16)
  begin

	/* build pool specific counter name, bufgrab_Nk (ie bufgrab_16k) */
	select @tmp_cntr = "bufgrab_" + convert(varchar(3), @j) + "k"

	select @tmp_total = @tmp_total + (SUM(value) * (@j / 2))
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name = @tmp_cntr

	select @j = @j * 2
  end
  
select @rptline = "      Pages by Lrg I/O Cached" +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0	/* Avoid Divide by Zero Errors after printout */
  begin
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name like "bufgrab_ref_%K" and
			field_name != "bufgrab_ref_2K"

	select @rptline = "      Pages by Lrg I/O Used" + space(2) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline
  end
print @blankline
print @blankline

print "    Dirty Read Behavior"
	
select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "buffer_%" and
		field_name = "level0_bufpredirty"

select @rptline = "      Page Requests" + space(10) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0	/* Avoid Divide by Zero Errors after printout */
  begin

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "access" and
			field_name = "dirty_read_restarts"

	select @rptline = "      Re-Starts" + space(10) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
	print @rptline
  end
print @blankline

/*
** Setup to analyze each "named cache" in alphabetic order ...
** First, build a temp table to map buffer id (ie counter groups
** buffer_0, buffer_1, etc.) to cache name.
*/
declare cache_info cursor for 
	select name
	  from master.dbo.sysconfigures
	  where parent=19 and
			config=19
	  for read only

create table #cachemap (
	cid smallint,
	name varchar(30),
	group_name varchar(30))

open cache_info
  fetch cache_info into @CacheName

while (@@sqlstatus = 0)
  begin
	select @CacheID = config_admin(15,0,0,0,NULL,@CacheName)
	insert into #cachemap values (@CacheID, @CacheName, "buffer_" + 
					convert(varchar(3), @CacheID))
	fetch cache_info into @CacheName
  end
close cache_info
deallocate cursor cache_info
/*
** Next, re-declare cursor to walk temp cache table in cache name
** order to print cache-specific statistics
*/ 
declare cache_info cursor for
	select cid, name, group_name
	  from #cachemap
	  order by name
	  for read only

open cache_info
fetch cache_info into @CacheID, @CacheName, @tmp_grp

/* Since all the cache spinlocks have the same name,
** rely on the fact that they are ordered by cache id.
*/
select P.field_id
		- (select min(field_id)
		from #tempmonitors where 
		field_name = P.field_name) as cid,
	P.value as grabs,
	W.value as waits,
	S.value as spins into #foo
from #tempmonitors P, #tempmonitors W, #tempmonitors S
where
	    P.group_name = "spinlock_p_0"
	and W.group_name = "spinlock_w_0"
	and S.group_name = "spinlock_s_0"
	and P.field_id = W.field_id
	and P.field_id = S.field_id
	and P.field_name = "Resource->rcaches[i]->cspin"

/* Create a #temp table to store information on currently configured
** pools for each cache.
*/
create table #pool_detail_per_cache (
	  io_size	char(8)		/* Size of buffer pool as '2', '4',
					** '8', '16' etc.
					*/
)

while (@@sqlstatus = 0)	/* { */
  begin
	print @subsection
	print @blankline
	select @rptline = space(2) + @CacheName
	print @rptline
	print "                                  per sec      per xact       count  %% of total"
	print @sum1line
	print @blankline

	select @tmp_int = waits, @tmp_int2 = grabs from #foo 
		where cid = @CacheID

	/* Store the sizes of pools configured for this cache */
	delete from #pool_detail_per_cache

	insert into #pool_detail_per_cache (io_size)
	select  convert(varchar(8),
			substring(co.comment, 1,
				  charindex("K", co.comment) - 1) )
	from master.dbo.sysconfigures co
	where co.parent = 19
	  and co.name = @CacheName
	  and co.comment like "%Buffer Pool%"

	if @tmp_int2 = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @rptline = "    Spinlock Contention" + space(14) +
						@na_str + space(11) +
						@na_str + space(9) +
						@na_str + space(5) +
						str(100.0 * @tmp_int / 
							@tmp_int2,5,1) 
							+ @psign
		print @rptline
	  end

	if @TotalSearches != 0
	  begin
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufsearch_calls"

		select @rptline = "    Utilization" + space(22) +
						@na_str + space(11) +
						@na_str + space(9) +
						@na_str + space(5) +
						str(100.0 * @tmp_int / 
							@TotalSearches,5,1) + 
						@psign
		print @rptline
	  end

	print @blankline

	print "    Cache Searches"

	select @tmp_total = value
	  from #tempmonitors
	  where group_name = @tmp_grp and
			field_name = "bufsearch_calls"

	if @tmp_total = 0		/* Avoid Divide by Zero Errors */
		print @zero_str
	else
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufsearch_finds"

		select @rptline = "      Cache Hits" + space(13) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		/* save hits for wash % and missed calc */
		select @tmp_int2 = @tmp_int

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufsearch_finds_in_wash"
	
		if @tmp_int2 != 0
		begin
			select @rptline = "         Found in Wash" + space(7) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_int2, 5, 1) + 
				@psign
			print @rptline
		end

		select @tmp_int = @tmp_total - @tmp_int2  /* missed searches */

		select @rptline = "      Cache Misses" + space(11) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline
      end	/* else @tmp_total = 0 */

	print @sum2line
	select @rptline = "    Total Cache Searches" + space(5) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10)
	print @rptline

	print @blankline
	print @blankline

	print "    Pool Turnover"

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = @tmp_grp and
			field_name like "bufgrab_%k"

	if @tmp_total = 0
		print @zero_str
	else

	  begin	/* { */
		/* init loop ctr to loop through all pool sizes (2,4,8,16) */
		select @j = 2
		while (@j <= 16)	/* { */
		  begin

			if @j > 2
				print @blankline

			/* 
			**  build pool specific counter name, 
			**  bufgrab_Nk (ie bufgrab_16k) 
			*/
			select @tmp_cntr = "bufgrab_" + 
					convert(varchar(3), @j) + "k"

			select @tmp_int = value
			  from #tempmonitors
			  where group_name = @tmp_grp and
					field_name = @tmp_cntr

			if @tmp_int != 0	/* { */
			  begin

				select @rptline = space(6) + 
					convert(char(3),@j) + "Kb Pool"
				print @rptline

				select @rptline = "          LRU Buffer Grab" +
					space(4) +
					str(@tmp_int / (@NumElapsedMs / 
						1000.0),12,1) + 
					space(2) +
					str(@tmp_int / 
						convert(real, @NumXacts),12,1)+
					space(2) +
					str(@tmp_int, 10) + space(5) +
					str(100.0 * @tmp_int / @tmp_total,5,1)+
					@psign
				print @rptline

				select @tmp_cntr = "bufgrab_dirty_" + 
					convert(varchar(3), @j) + "k"

				select @tmp_int2 = value
				  from #tempmonitors
				  where group_name = @tmp_grp and
						field_name = @tmp_cntr

				select @rptline = space(12) + "Grabbed Dirty" +
					space(4) +
					str(@tmp_int2 / (@NumElapsedMs / 
						1000.0),12,1) + 
					space(2) +
					str(@tmp_int2 / 
						convert(real, @NumXacts),12,1)+
					space(2) +
					str(@tmp_int2, 10) + space(5) +
					str(100.0 * @tmp_int2 / @tmp_int,5,1) +
					@psign
				print @rptline

			  end	/* } if @tmp_int != 0 */
			  
			/* get next pool size (power of 2) */
			select @j = @j * 2 

		end		/* } while */

	  end	/* } else @tmp_total != 0 */

	print @sum2line		/* calc cache turnover percent of all caches */
	select @rptline = "    Total Cache Turnover" + space(5) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10)
	print @rptline
	print @blankline
	print @blankline

	print "    Buffer Wash Behavior"

	select @tmp_total = value
	  from #tempmonitors
	  where group_name = @tmp_grp and
			field_name = "bufwash_throughput"

	if @tmp_total != 0	/* any buffers move through wash yet? */
	  begin

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufwash_pass_clean"

		select @rptline = "      Buffers Passed Clean" + space(3) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufwash_pass_writing"

		select @rptline = "      Buffers Already in I/O " +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufwash_write_dirty"

		select @rptline = "      Buffers Washed Dirty   " +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline
	  end
	else
		print "      Statistics Not Available - No Buffers Entered Wash Section Yet"

	print @blankline
	print @blankline
	
	print "    Cache Strategy"

	/* 
	** Sum all buf unkeeps to look at % of buffers following 
	** MRU vs Discard Strategy 
	*/
	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = @tmp_grp and
			field_name IN ("bufunkeep_lru", "bufunkeep_mru")

	if @tmp_total != 0
	  begin
		select @tmp_int = SUM(value)
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufunkeep_lru"

		select @rptline = "      Cached (LRU) Buffers   " +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int = SUM(value)
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "bufunkeep_mru"

		select @rptline = "      Discarded (MRU) Buffers"+
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline
	  end
	else
		print "      Statistics Not Available - No Buffers Displaced Yet"

	print @blankline
	print @blankline

	print "    Large I/O Usage"	

	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = @tmp_grp and
			field_name = "prefetch_req"

	if @tmp_total = 0
		print @zero_str
	else
	  begin

		select @tmp_int = SUM(value)
		  from #tempmonitors
		  where group_name = @tmp_grp and field_name IN
			 ("prefetch_as_requested", "prefetch_page_realigned")

		select @rptline = "      Large I/Os Performed" + space(3) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + 
				@psign
		print @rptline

		select @tmp_int2 = @tmp_total - @tmp_int

		select @rptline = "      Large I/Os Denied" + space(6) +
				str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1)+
				space(2) +
				str(@tmp_int2 / convert(real, @NumXacts),12,1)+
				space(2) +
				str(@tmp_int2, 10) + space(5) +
				str(100.0 * @tmp_int2 / @tmp_total,5,1) + 
				@psign
		print @rptline

		print @sum2line 
		select @rptline = "    Total Large I/O Requests " +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_total,10)
		print @rptline
	  end	/* else */

	print @blankline
	print @blankline

	print "    Large I/O Detail"

	/*
	**  default to NO large pools found for this cache 
	*/
	select @lrgpool = 0	
	/* 
	** init loop counter to loop through all large I/O pool 
	** sizes (4,8,16) 
	*/
	select @j = 4		

	while (@j <= 16)	/* { */
	  begin

	  /* Check that the current cache has a pool configured of size @j */
	  select @gt2Kpool = count(*)
	  from #pool_detail_per_cache pd
	  where pd.io_size = convert(varchar(8), @j)

	  if (@gt2Kpool > 0)
	  begin			/* { */

		/* Remember that we _did_ find a large I/O pool */
		select @lrgpool = 1

		/* 
		** build pool specific counter name, 
		** bufgrab_Nk (ie bufgrab_16k) 
		*/
		select @tmp_cntr = "bufgrab_" + convert(varchar(3), @j) + "k"

		select @tmp_total = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = @tmp_cntr

		print @blankline
		select @rptline = space(5) + convert(char(4),@j) + 
				"Kb Pool"
		print @rptline

		if @tmp_total = 0
		begin
			select @rptline = "        Pages Cached" + space(18) +
					  ltrim(@zero_str)
			print @rptline

			select @rptline = "        Pages Used" + space(20) +
					  ltrim(@zero_str)
			print @rptline
		end

		else
		  begin

			/* turn # of masses into # of 2kb pages */
			select @tmp_total = @tmp_total * (@j / 2)	

			select @rptline = "        Pages Cached" + space(9) +
				str(@tmp_total / 
					(@NumElapsedMs / 1000.0),12,1) + 
				space(2) +
				str(@tmp_total / 
					convert(real, @NumXacts),12,1) + 
				space(2) +
				str(@tmp_total,10) + space(7) +
				@na_str
			print @rptline

			select @tmp_cntr = "bufgrab_ref_" + 
				convert(varchar(3), @j) + "K"

			select @tmp_int = value
			  from #tempmonitors
			  where group_name = @tmp_grp and
					field_name = @tmp_cntr

			select @rptline = "        Pages Used" + space(11) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
			print @rptline
			print @blankline
		  end

		end	/* } if @gt2Kpool > 0 */

		select @j = @j * 2	/* get next pool size */

	  end	/* } while (@j <= 16) */

	if @lrgpool = 0		/* No large pools in this cache */
	  begin
		print "      No Large Pool(s) In This Cache"
	  end

	print @blankline


	print "    Dirty Read Behavior"
	
	select @tmp_total = SUM(value)
	  from #tempmonitors
	  where group_name = @tmp_grp and
			field_name = "level0_bufpredirty"

	select @rptline = "	  Page Requests" + space(6) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total,10) + space(7) +
			@na_str
	print @rptline
	print @blankline

	fetch cache_info into @CacheID,  @CacheName, @tmp_grp

  end  /* } while @@sqlstatus */

close cache_info
deallocate cursor cache_info

return 0
go
exec sp_procxmode 'sp_sysmon_dcache', 'anymode'
go
grant execute on sp_sysmon_dcache to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_pcache')
begin
	drop procedure sp_sysmon_pcache
end
go
print "Installing sp_sysmon_pcache"
go

/* This stored procedure produces a report containing a summary of
** of how effectively the procedure cache is being utilized.
*/
create procedure sp_sysmon_pcache
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "---------------------------  ------------  ------------  ----------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"

print @blankline

print "Procedure Cache Management        per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = value
  from #tempmonitors
  where group_name = "procmgr" and
		field_name = "procedure_requests"

select @rptline = "  Procedure Requests" + space(9) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total !=0
  begin
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "procmgr" and
			field_name = "procedure_reads"

	select @rptline = "  Procedure Reads from Disk" + space(2) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "procmgr" and
			field_name = "procedure_writes"

	select @rptline = "  Procedure Writes to Disk" + space(3) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "procmgr" and
			field_name = "procedure_removes"

	select @rptline = "  Procedure Removals" + space(9) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str

	print @rptline

  end
print @blankline
return
go
exec sp_procxmode 'sp_sysmon_pcache', 'anymode'
go
grant execute on sp_sysmon_pcache to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_memory')
begin
	drop procedure sp_sysmon_memory
end
go
print "Installing sp_sysmon_memory"
go

/* This stored procedure produces a report containing a summary of
** memory use within the SQL server's pool of available memory.
*/
create procedure sp_sysmon_memory
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @tmp_int int		/* temp var for integer storage */
declare @sum1line char(80)	/* string to delimit total lines without 
				percent calc on printout */	
declare @blankline char(1)	/* to print blank line */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "---------------------------  ------------  ------------  ----------  ----------"
select @blankline  = " "
select @na_str     = "n/a"

print @blankline

print "Memory Management                 per sec      per xact       count  %% of total"
print @sum1line

select @tmp_int = value
  from #tempmonitors
  where group_name = "memory" and
		field_name = "mempages_alloced"

select @rptline = "  Pages Allocated" + space(12) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

select @tmp_int = value
  from #tempmonitors
  where group_name = "memory" and
		field_name = "mempages_freed"

select @rptline = "  Pages Released" + space(13) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int, 10) + space(7) +
			@na_str
print @rptline

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_memory', 'anymode'
go
grant execute on sp_sysmon_memory to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_recovery')
begin
	drop procedure sp_sysmon_recovery
end
go
print "Installing sp_sysmon_recovery"
go

/* This stored procedure produces a report containing a summary of
** checkpoint and housekeeper activity.
*/
create procedure sp_sysmon_recovery
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_int2 int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

print @blankline

print "Recovery Management"
print "-------------------"
print @blankline

print "  Checkpoints                     per sec      per xact       count  %% of total"
print @sum1line

select @tmp_int = value
  from #tempmonitors
  where group_name = "access" and
		field_name = "normal_database_checkpoints"

select @tmp_int2 = value
  from #tempmonitors
  where group_name = "housekeeper" and
		field_name = "free_database_checkpoints"

select @tmp_total = @tmp_int + @tmp_int2

if @tmp_total = 0 
	print @zero_str
else
  begin
	select @rptline = "    # of Normal Checkpoints" + space(2) +
			str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
			space(2) +
			str(@tmp_int / convert(real, @NumXacts),12,1) +
			space(2) +
			str(@tmp_int, 10) + space(5) +
			str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline

	select @rptline = "    # of Free Checkpoints" + space(4) +
			str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int2 / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int2, 10) + space(5) +
			str(100.0 * @tmp_int2 / @tmp_total,5,1) + @psign
	print @rptline

	print @sum1line
	select @rptline = "  Total Checkpoints" + space(10) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
	print @rptline
	print @blankline
	
	select @tmp_total = value
	  from #tempmonitors
	  where group_name = "access" and
			field_name = "time_todo_normal_checkpoints"


	if @tmp_int != 0	/* any normal checkpoints ? */
	  begin
		select @rptline = "  Avg Time per Normal Chkpt" + space(2) +
				str(convert(real,@tmp_total) / @tmp_int,12,5) +
				" seconds"
		print @rptline
	  end

	select @tmp_total = value
	  from #tempmonitors
	  where group_name = "housekeeper" and
			field_name = "time_todo_free_checkpoints"


	if @tmp_int2 != 0	/* any housekeeper checkpoints ? */
	  begin
		select @rptline = "  Avg Time per Free Chkpt" + space(4) +
			str(convert(real,@tmp_total) / @tmp_int2,12,5) + 
			" seconds"
		print @rptline
	  end
  end

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_recovery', 'anymode'
go
grant execute on sp_sysmon_recovery to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_diskio')
begin
	drop procedure sp_sysmon_diskio
end
go
print "Installing sp_sysmon_diskio"
go

/* This stored procedure produces a report containing a summary of
** of disk activity.
*/
create procedure sp_sysmon_diskio
	@NumEngines tinyint,	/* number of engines online */
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @SybDiskName char(30)	/* cursor var for logical disk name - 
				** sysdevices.name */
declare @PhyDiskName varchar(127) /* cursor var for physical disk name - 
				  ** sysdevices.phyname */

declare @i smallint		/* loop index to iterate through multi-group
				**  counters (engine, disk, & buffer) */
declare @tmp_grp varchar(25)	/* temp var for build group_name's - ie., 
				** engine_N, disk_N */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_int2 int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @subsection char(80)	/* delimit disk sections */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @subsection = "    ---------------------------------------------------------------------------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

print @blankline
print "Disk I/O Management"
print "-------------------"
print @blankline
print "  Max Outstanding I/Os            per sec      per xact       count  %% of total"
print @sum1line

select @tmp_int = value
  from #tempmonitors
  where group_name = "kernel" and
		field_name = "max_outstanding_AIOs_server"

select @rptline = "    Server" + space(28) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(@tmp_int, 10) + space(7) +
				@na_str
print @rptline

select @i = 0
while @i < @NumEngines		/* for each engine */
  begin
	/* build group_name string */
	select @tmp_grp = "engine_" + convert(varchar(2), @i)
  
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = @tmp_grp and
            field_name = "max_outstanding_AIOs_engine"
  
	select @rptline = "    Engine " + convert(char(2), @i) + space(25) +
					@na_str + space(11) +
					@na_str + space(2) +
					str(@tmp_int, 10) + space(7) +
					@na_str
	print @rptline

	select @i = @i + 1
  end

print @blankline
print @blankline
print "  I/Os Delayed by"

select @tmp_int = value
  from #tempmonitors
  where group_name = "kernel" and
		field_name = "udalloc_sleeps"

select @rptline = "    Disk I/O Structures" + space(15) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(@tmp_int, 10) + space(7) +
				@na_str
print @rptline

select @tmp_int = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "AIOs_delayed_due_to_server_limit"

select @rptline = "    Server Config Limit" + space(15) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(@tmp_int, 10) + space(7) +
				@na_str
print @rptline

select @tmp_int = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "AIOs_delayed_due_to_engine_limit"

select @rptline = "    Engine Config Limit" + space(15) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(@tmp_int, 10) + space(7) +
				@na_str
print @rptline

select @tmp_int = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "AIOs_delayed_due_to_os_limit"

select @rptline = "    Operating System Limit" + space(12) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(@tmp_int, 10) + space(7) +
				@na_str
print @rptline
print @blankline
print @blankline

select @tmp_int = value
  from #tempmonitors
  where group_name = "kernel" and
		field_name = "udalloc_calls"

select @rptline = "  Total Requested Disk I/Os" + space(2) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(7) +
				@na_str
print @rptline
print @blankline
print "  Completed Disk I/O's"

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "total_dpoll_completed_aios"

if @tmp_total = 0
	print @zero_str
else
  begin
	select @i = 0
	while @i < @NumEngines		/* for each engine */
	  begin
		/* build group_name string */
		select @tmp_grp = "engine_" + convert(varchar(2), @i)
  
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "total_dpoll_completed_aios"
  
		select @rptline = "    Engine " + convert(char(2), @i) + 
				space(16) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @i = @i + 1
	  end	/* while loop */
  end	/* else */

print @sum1line

select @rptline = "  Total Completed I/Os" + space(7) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10)
print @rptline
print @blankline
print @blankline
print "  Device Activity Detail"
print "  ----------------------"
print @blankline

/* get total number of I/Os to all devices to calc each device's percentage */
select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "disk_%" and
		(field_name = "total_reads" or field_name = "total_writes")

if @tmp_total = 0
	print "    No Disk I/O in Given Sample Period"
else
  begin

	/* 
	**  Declare cursor to sysdevices ordered by physical name - 
	**  skip dump devices  (ie status = 16)
	*/ 
	declare disk_info cursor for
		select name, phyname, "disk_" + 
			convert(varchar(4), low / 16777216)
		  from master.dbo.sysdevices
		  where (status & 16) != 16	
		  order by phyname
		  for read only

	open disk_info
	fetch disk_info into @SybDiskName, @PhyDiskName, @tmp_grp

	while (@@sqlstatus = 0)
	  begin

		select @rptline = space(2) + substring(@PhyDiskName, 1, 76)
		print @rptline
		select @rptline = space(2) + convert(char(25), 
			substring(@SybDiskName, 1, 25)) + 
			"       per sec      per xact       count  %% of total"
		print @rptline

		print @sum1line

		select @tmp_int2 = SUM(value)
		  from #tempmonitors
		  where group_name = @tmp_grp and
				(field_name = "total_reads" or 
					field_name = "total_writes")

		if @tmp_int2 = 0
			print @zero_str
		else
		  begin
			select @tmp_int = value
			  from #tempmonitors
			  where group_name = @tmp_grp and
					field_name = "total_reads"

			select @rptline = "    Reads" + space(20) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_int2,5,1) + @psign
			print @rptline

			select @tmp_int = value
			  from #tempmonitors
			  where group_name = @tmp_grp and
					field_name = "total_writes"

			select @rptline = "    Writes" + space(19) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_int2,5,1) + @psign
			print @rptline

		  end	/* else @tmp_int2 != 0 */

		print @sum1line

		select @rptline = "  Total I/Os" + space(17) +
			str(@tmp_int2 / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_int2 / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_int2, 10) + space(5) +
			str(100.0 * @tmp_int2 / @tmp_total,5,1) + @psign
		print @rptline
		print @blankline

		select @tmp_int2 = SUM(value)
		  from #tempmonitors
		  where group_name = @tmp_grp and
			(field_name = "p_hits" or field_name = "p_misses")

		if @tmp_int2 != 0
		  begin

			select @tmp_int = value
			  from #tempmonitors
			  where group_name = @tmp_grp and
					field_name = "p_hits"

			select @rptline = "  Device Semaphore Granted" + 
				space(3) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_int2,5,1) + @psign
			print @rptline

			select @tmp_int = value
			  from #tempmonitors
			  where group_name = @tmp_grp and
					field_name = "p_misses"

			select @rptline = "  Device Semaphore Waited" + 
				space(4) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_int2,5,1) + @psign
			print @rptline
		  end	/* else @tmp_int2 != 0 */ 

		print @blankline
		print @subsection
		print @blankline

		fetch disk_info into @SybDiskName, @PhyDiskName, @tmp_grp

	  end	/* while @@sqlstatus */

	close disk_info 
	deallocate cursor disk_info

  end	/* else @tmp_total != 0 */

return 0
go
exec sp_procxmode 'sp_sysmon_diskio', 'anymode'
go
grant execute on sp_sysmon_diskio to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_netio')
begin
	drop procedure sp_sysmon_netio
end
go
print "Installing sp_sysmon_netio"
go

/* This stored procedure produces a report containing a summary of
** network activity.
*/
create procedure sp_sysmon_netio
	@NumEngines tinyint,	/* number of engines online */
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @i smallint		/* loop index to iterate through multi-group 
				** counters (engine, disk, & buffer) */
declare @tmp_grp varchar(25)	/* temp var for build group_names 
				** ie. engine_N, disk_N */
declare @tmp_int int		/* temp var for integer storage */
declare @tmp_int2 int		/* temp var for integer storage */
declare @tmp_total int		/* temp var for summing 'total #s' data */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @subsection char(80)	/* delimit disk sections */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" for 
				** printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @subsection = "  -----------------------------------------------------------------------------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"

print @blankline
print "Network I/O Management"
print "----------------------"
print @blankline

select @tmp_total = value
  from #tempmonitors
  where group_name = "kernel" and
		field_name = "ksalloc_calls"

select @rptline = "  Total Network I/O Requests " + 
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10) + space(7) +
			@na_str
print @rptline

if @tmp_total != 0
  begin
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "kernel" and
			field_name = "ksalloc_sleeps"

	select @rptline = "    Network I/Os Delayed" + space(5) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
	print @rptline
  end
print @blankline
print @blankline

print "  Total TDS Packets Received      per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "no_packets_received"

if @tmp_total = 0
	print @zero_str
else
  begin
	select @i = 0
	while @i < @NumEngines		/* for each engine */
	  begin
		/* build group_name string */
		select @tmp_grp = "engine_" + convert(varchar(2), @i)
  
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "no_packets_received"
  
		select @rptline = "    Engine " + convert(char(2), @i) + 
				space(16) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @i = @i + 1
	  end	/* while loop */
  end	/* else */

print @sum1line

select @rptline = "  Total TDS Packets Rec'd" + space(4) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10)
print @rptline
print @blankline
print @blankline

/* 
** save total packets rec'd for avg bytes / pkt calc 
*/ 
select @tmp_int2 = @tmp_total	

print "  Total Bytes Received            per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "no_bytes_received"

if @tmp_total = 0
	print @zero_str
else
  begin
	select @i = 0
	while @i < @NumEngines		/* for each engine */
	  begin
		/* build group_name string */
		select @tmp_grp = "engine_" + convert(varchar(2), @i)
  
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "no_bytes_received"
  
		select @rptline = "    Engine " + convert(char(2), @i) + 
				space(16) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @i = @i + 1
	  end	/* while loop */
  end	/* else */

print @sum1line

select @rptline = "  Total Bytes Rec'd" + space(10) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10)
print @rptline
print @blankline
print @blankline

if @tmp_int2 != 0		/* Avoid divide by zero. */
  begin
	select @rptline = "   Avg Bytes Rec'd per Packet" + space(10) +
				@na_str + space(11) +
				@na_str + space(2) +
				str(@tmp_total / @tmp_int2, 10) + space(7) +
				@na_str
	print @rptline
	print @blankline
  end
print @subsection
print @blankline

print "  Total TDS Packets Sent          per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "no_packets_sent"

if @tmp_total = 0
	print @zero_str
else
  begin
	select @i = 0
	while @i < @NumEngines		/* for each engine */
	  begin
		/* build group_name string */
		select @tmp_grp = "engine_" + convert(varchar(2), @i)
  
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "no_packets_sent"
  
		select @rptline = "    Engine " + convert(char(2), @i) + 
				space(16) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @i = @i + 1
	  end	/* while loop */
  end	/* else */

print @sum1line

select @rptline = "  Total TDS Packets Sent" + space(5) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10)
print @rptline
print @blankline
print @blankline

/* save total packets sent for avg bytes / pkt calc */ 
select @tmp_int2 = @tmp_total

print "  Total Bytes Sent                per sec      per xact       count  %% of total"
print @sum1line

select @tmp_total = SUM(value)
  from #tempmonitors
  where group_name like "engine_%" and
		field_name = "no_bytes_sent"

if @tmp_total = 0
	print @zero_str
else
  begin
	select @i = 0
	while @i < @NumEngines		/* for each engine */
	  begin
		/* build group_name string */
		select @tmp_grp = "engine_" + convert(varchar(2), @i)
  
		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
				field_name = "no_bytes_sent"
  
		select @rptline = "    Engine " + convert(char(2), @i) + 
				space(16) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @tmp_total,5,1) + @psign
		print @rptline

		select @i = @i + 1
	  end	/* while loop */
  end	/* else */

print @sum1line

select @rptline = "  Total Bytes Sent" + space(11) +
			str(@tmp_total / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@tmp_total / convert(real, @NumXacts),12,1) + 
			space(2) +
			str(@tmp_total, 10)
print @rptline
print @blankline
print @blankline

if @tmp_int2 != 0 		/* Avoid divide by zero. */
  begin
	select @rptline = "  Avg Bytes Sent per Packet" + space(11) +
					@na_str + space(11) +
					@na_str + space(2) +
					str(@tmp_total / @tmp_int2, 10) + 
					space(7) +
					@na_str
	print @rptline
	print @blankline
  end

return 0
go
exec sp_procxmode 'sp_sysmon_netio', 'anymode'
go
grant execute on sp_sysmon_netio to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon_taskmgmt')
begin
	drop procedure sp_sysmon_taskmgmt
end
go
print "Installing sp_sysmon_taskmgmt"
go

/* This stored procedure produces a report describing the scheduling
** of user tasks.
**
*/
create procedure sp_sysmon_taskmgmt

	@NumEngines tinyint,	/* number of engines online */
	@NumElapsedMs int,	/* for "per Elapsed second" calculations */
	@NumXacts int		/* for per transactions calculations */
as

/* --------- declare local variables --------- */
declare @NumTaskSwitch int	/* Total Number of Task Context Switches 
				** across all engines */
declare @KnownTaskSwitch int	/* Count of Number of Task Context Switches 
				** by Known Causes */
declare @i smallint		/* loop index to iterate through multi-group 
				** counters (engine, disk, & buffer) */
declare @tmp_grp varchar(25)	/* temp var for building group_names 
				** ie. engine_N, disk_N */
declare @tmp_int int		/* temp var for integer storage */
declare @sum1line char(80)	/* string to delimit total lines without 
				** percent calc on printout */	
declare @sum2line char(67)	/* string to delimit total lines with percent 
				** calc on printout */
declare @blankline char(1)	/* to print blank line */
declare @psign char(3)		/* hold a percent sign (%) for print out */
declare @na_str char(3)		/* holds 'n/a' for 'not applicable' strings */
declare @zero_str char(80)	/* hold an output string for zero "  0.0" 
				** for printing zero "% of total" */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */

select @sum1line   = "  -------------------------  ------------  ------------  ----------  ----------"
select @sum2line   = "  -------------------------  ------------  ------------  ----------"
select @blankline  = " "
select @psign      = " %%"		/* extra % symbol because '%' is escape char in print statement */
select @na_str     = "n/a"
select @zero_str   = "                                      0.0           0.0           0       n/a"


/* =========================  Task Management Section ==================== */
print @blankline
print "Task Management                   per sec      per xact       count  %% of total"
print @sum1line
print @blankline
/*
** ------ Connections Opened (Closed Not Available in counters) ------
*/
select @tmp_int = value
from #tempmonitors
where group_name = "kernel" and
	  field_name = "processes_created"

select @rptline="  Connections Opened" + space(9)
				+ str(@tmp_int/(@NumElapsedMs/1000.0),12,1)
				+ space(2)
				+ str(@tmp_int/convert(real,@NumXacts),12,1)
				+ space(2)
				+ str(@tmp_int, 10) + space(7)
				+ @na_str
print @rptline
print @blankline
print @blankline

print "  Task Context Switches by Engine"

select @NumTaskSwitch = SUM(value)
  from #tempmonitors 
  where group_name like "engine_%" and
		field_name = "context_switches"

if @NumTaskSwitch = 0	/* Avoid divide by zero errors - print zero's */
  print @zero_str

else              
  begin
	select @i = 0
	while @i < @NumEngines		/* for each engine */
	  begin
		/* build group_name string */
		select @tmp_grp = "engine_" + convert(varchar(2), @i)

		select @tmp_int = value
		  from #tempmonitors
		  where group_name = @tmp_grp and
	  			field_name = "context_switches"

		select @rptline = "    Engine "+convert(char(2),@i)+space(16) +
				str(@tmp_int/(@NumElapsedMs/1000.0),12,1) + 
				space(2) +
				str(@tmp_int/convert(real,@NumXacts),12,1) + 
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
		print @rptline
		select @i = @i + 1
	  end	/* while */

	if @NumEngines > 1
	  begin
		print @sum2line 
		select @rptline = "    Total Task Switches:" + space(5) +
			str(@NumTaskSwitch / (@NumElapsedMs / 1000.0),12,1) + 
			space(2) +
			str(@NumTaskSwitch / convert(real,@NumXacts),12,1) + 
			space(2) +
			str(@NumTaskSwitch,10)
		print @rptline
	  end /* if @NumEngines > 1*/
	print @blankline
	print @blankline

	/* 
	** Break Down All Task Context Switches by Cause 
	*/
	print "  Task Context Switches Due To:"

	/* init count of known context switches */
	select @KnownTaskSwitch = 0		

	/* 
	** Context Switch Due to Task Yields (Voluntary)
	*/
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "kernel" and
	  		field_name = "yields"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Voluntary Yields" + space(9) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/*
	**  Context Switch Due to Cache Search Misses resulting in a read
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name = "bufread_read_waits"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Cache Search Misses" + space(6) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) +
				@psign
	print @rptline

	/* 
	** Context Switch Due to Disk Writes 
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name in ("write_waits", "hk_write_waits", 
					"restart_io_waits")

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    System Disk Writes" + space(7) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/*  Context Switch Due to I/O pacing
	**
	**  In other words, we started MAXWRITEDES I/Os and now we are waiting
	**  for them to complete before starting the next batch.  The server 
	**  works in batches to avoid flooding the I/O subsystem.  The size 
	**  of the batch, MAXWRITEDES, is tuneable.
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name in ("my_start_waits_log", 
					"my_start_waits_non-log", 
					"my_other_waits_non-log")

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    I/O Pacing" + space(15) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) +
				@psign
	print @rptline

	/*
	** Context Switch Due to DB Lock Contention
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			field_name like "waited_%" and
			field_name not like "waited_%_ADDR"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Logical Lock Contention  " +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) +
				@psign
	print @rptline

	/* 
	** Context Switch Due to Address Lock Contention 
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "lock" and
			field_name like "waited_%_ADDR"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Address Lock Contention  " +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline


	/* 
	** Context Switch Due to Blocking on Log Semaphore 
	*/
	select @tmp_int = value
	  from #tempmonitors
	  where group_name = "xls" and
			field_name = "log_lock_waited"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Log Semaphore Contention " +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* 
	** Context Switch Due to Group Commit Sleeps 
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name IN ("my_other_waits_log", 
					"log_lastpage_pending_io_sleeps")

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Group Commit Sleeps" + space(6) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* 
	** Context Switch Due to Last Log Page Writes 
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and
			field_name = "last_log_page_writes"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Last Log Page Writes" + space(5) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* Context Switch Due to Modify Conflicts 
	**
	**  In other words, a task wants to perform an operation on a page 
	**  (i.e. write it), but can't because another task is in the middle 
	**  of modifying it.
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "buffer_%" and field_name in 
		  ("changing_state_waits", "bufwrite_changing_waits", 
		   "bufpredirty_write_waits", "bufpredirty_changing_waits", 
		   "bufnewpage_changing_waits", "ind_bufguess_changing_waits",
		   "ind_bufguess_writing_waits")

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Modify Conflicts" + space(9) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* 
	** Context Switch Due to Disk Device Contention 
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name like "disk_%" and
			field_name = "p_misses"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    I/O Device Contention" + space(4) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* 
	** Context Switch Due to Network Packets Received
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "network" and
			field_name = "total_packets_received"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Network Packet Received" + space(2) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* 
	** Context Switch Due to Network Packets Sent
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "network" and
			field_name = "total_packets_sent"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    Network Packet Sent" + space(6) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* 
	** Context Switch Due to Lookups on sysindexes
	*/
	select @tmp_int = SUM(value)
	  from #tempmonitors
	  where group_name = "sysind" and
			field_name like "ind_bufguess%"

	select @KnownTaskSwitch = @KnownTaskSwitch + @tmp_int

	select @rptline = "    SYSINDEXES Lookup" + space(8) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

	/* 
	** Context Switch Due to Other Causes
	*/
	select @tmp_int = @NumTaskSwitch - @KnownTaskSwitch
	select @rptline = "    Other Causes" + space(13) +
				str(@tmp_int / (@NumElapsedMs / 1000.0),12,1) +
				space(2) +
				str(@tmp_int / convert(real, @NumXacts),12,1) +
				space(2) +
				str(@tmp_int, 10) + space(5) +
				str(100.0 * @tmp_int / @NumTaskSwitch,5,1) + 
				@psign
	print @rptline

  end		/* else @NumTaskSwitch != 0 */

print @blankline
return 0
go
exec sp_procxmode 'sp_sysmon_taskmgmt', 'anymode'
go
grant execute on sp_sysmon_taskmgmt to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_sysmon')
begin
	drop procedure sp_sysmon
end
go
print "Installing sp_sysmon"
go

/* Messages for sp_sysmon
**
** 18179, "Invalid parameter. Usage: sp_sysmon {1-10}"
** 18127, "You must have System Administrator (SA) role to execute this 
**	   stored procedure."
** 17260, "Can't run %1! from within a transaction."
*/

/*
** In order to load the stored procedures that sysmon references,
** the temporary table #tempmonitors must exist (because they
** reference it).  If it exists at the time sp_sysmon is loaded,
** the load will fail because of the "select into" below.
**
** Drop the table now.
**
*/
if (exists (select * from tempdb.dbo.sysobjects where id =
		(select object_id("#tempmonitors"))))
begin
	drop table #tempmonitors
end
go

create procedure sp_sysmon
  @SamplePeriod tinyint		/* Supported Values Are 1 - 10 (minutes). */
as

/* --------- declare local variables --------- */
declare @msg varchar(250)	/* error msg output */
declare @status int		/* hold sproc status codes */
declare @ClrStatTime datetime	/* time monitor counters cleared */
declare @GetStatTime datetime	/* time monitor counters sampled */
declare @NumXacts int		/* for per transactions calculations */
declare @NumElapsedMs int	/* for "per Elapsed second" calculations */
declare @NumEngines tinyint	/* number of engines online */
declare @section char(80)	/* string to delimit sections on printout */
declare @blankline char(1)	/* to print blank line */
declare @rptline char(80)	/* formatted stats line for print statement */

/* --------- Setup Environment --------- */
set nocount on			/* disable row counts being sent to client */
select @section = "==============================================================================="
select @blankline = " "

/*
** Validate Parameters
*/
if @SamplePeriod < 1 or @SamplePeriod > 10
  begin
	exec sp_getmessage 18179, @msg output
	print @msg
	return 1
  end
  
/* 
** Check if OK to Run 
*/
if proc_role("sa_role") != 1 
  begin
	/* 18127, "You must have System Administrator (SA) role to execute this stored procedure." */
	exec sp_getmessage 18127, @msg output
	print @msg, "sp_sysmon"
	return 1
  end

/* 
** In a transaction?, disallow since it might make recovery impossible
*/
if @@trancount > 0
  begin
	/* 17260, "Can't run %1! from within a transaction." */
	exec sp_getmessage 17260, @msg output
	print @msg, "sp_sysmon"
	return 1
  end
else
  set chained off

set transaction isolation level 1


/* 
** Clear out all monitor counters
*/
dbcc monitor("clear", "all", "on")
dbcc monitor("clear", "spinlock_s", "on")
select @ClrStatTime = getdate()


/* 
** Sleep while accumulating counter statistics
*/
if @SamplePeriod = 1
  waitfor delay "00:01:00"		/* HARD CODED - ADJUST AS NECESSARY */
else if @SamplePeriod = 2		/* waitfor delay can't take params, */
  waitfor delay "00:02:00"		/* only constants.		    */
else if @SamplePeriod = 3
  waitfor delay "00:03:00"
else if @SamplePeriod = 4
  waitfor delay "00:04:00"
else if @SamplePeriod = 5
  waitfor delay "00:05:00"
else if @SamplePeriod = 6
  waitfor delay "00:06:00"
else if @SamplePeriod = 7
  waitfor delay "00:07:00"
else if @SamplePeriod = 7
  waitfor delay "00:07:00"
else if @SamplePeriod = 8
  waitfor delay "00:08:00"
else if @SamplePeriod = 9
  waitfor delay "00:09:00"
else if @SamplePeriod = 10
  waitfor delay "00:10:00"

/*
**  Sample Performance Stats
*/
dbcc monitor("sample", "spinlock_s", "off")
dbcc monitor("sample", "all", "off")
select @GetStatTime = getdate()
dbcc monitor("select", "spinlock_s", "on")
dbcc monitor("select", "all", "on")
dbcc traceon(8399)

/* 
** Save master.dbo.sysmonitors into a temp table to minimize risk of
** another user clearing sample during sp_sysmon processing.
*/
select *
  into #tempmonitors
  from master.dbo.sysmonitors holdlock
  
create clustered index #tempmon_ndx on #tempmonitors(group_name, field_name)

/* 
** Get General Information Needed for Calculations
**
** # of Online Engines for Looping Through All Counter Groups for Engines
**       config = 126 "max online engines"
**       config = 165 "current online engines"
*/
select @NumEngines = value
  from master.dbo.syscurconfigs
  where config = 126

/* Number of Milliseconds (Wall Clock Time) Actually Elapsed during Sampling */
select @NumElapsedMs = datediff(ms, @ClrStatTime, @GetStatTime)

/*
**	Name:		Number of Transactions 
**	Descrip:	Measures the number of committed transactions, both 
**			explicit via BEGIN TRAN and COMMIT TRAN as well as 
**			implicit via single statement DML.  Used to report 
**			not just how much work has been done within the sample 
**			but, more importantly, as a measure of viewing other
**			statistics with a common denominator (ie., I/Os per
**			transaction).  This provides a common way of judging 
**			the effects of making changes within a controlled test 
**			environment.
**
**			For example, what effect does adding memory have on I/O
**			rates.
**	Calc:		access.xacts
**	Caveats:	This counter is also incremented once for each
**			"sub-transaction" participating in a multi-DB 
**			transaction.
**	Tuning:		None, informational only to provide a frame of 
**			reference for evaluating other statistics.
*/
select @NumXacts = value 
  from #tempmonitors
  where group_name = "access" and
        field_name = "xacts"

if @NumXacts = 0
  select @NumXacts = 1		/* avoid divide by 0 for all per xact calcs */

/*
** Print Report Header
*/
print @section
print "              Sybase SQL Server System Performance Report"
print @section 
print @blankline

select @rptline = convert(char(12), @GetStatTime, 107)
print "Run Date                     %1!", @rptline
select @rptline = convert(char(8), @ClrStatTime, 108)
print "Statistics Cleared at            %1!", @rptline
select @rptline = convert(char(8), @GetStatTime, 108)
print "Statistics Sampled at            %1!", @rptline
select @rptline = "Sample Interval" + space(20) + convert(char(2), 
		@SamplePeriod) +  " min."
print @rptline
print @blankline 

print @section
exec @status = sp_sysmon_kernel @NumEngines, @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_taskmgmt @NumEngines, @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_xactsum @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_xactmgmt @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_index @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_locks @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_dcache @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_pcache @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_memory @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_recovery @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print @section
exec @status = sp_sysmon_diskio @NumEngines, @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end


print @section
exec @status = sp_sysmon_netio @NumEngines, @NumElapsedMs, @NumXacts
if @status = 1		/* fatal error - abort run */
  begin
	/* Subordinate stored procedures print their own messages. */
	return 1
  end

print "=============================== End of Report ================================="

return 0
go
exec sp_procxmode 'sp_sysmon', 'anymode'
go
grant execute on sp_sysmon to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_shmdumpsize')
begin
	drop procedure sp_shmdumpsize
end
go
print "Installing sp_shmdumpsize"
go

/*
** SP_SHMDUMPSIZE
**
** This stored procedure calculates the estimated size for a shared memory
** dump file.  It is not meant to be executed from the command line, but
** is called by the sp_shmdumpconfig stored procedure when displaying
** current configuration inforamtion.
**
** History:
** 16dec96	pdorfman	written
*/

create procedure sp_shmdumpsize
@pagecache	varchar(20),	/* Page cache setting for condition           */
@proccache	varchar(20),	/* Procedure cache setting for condition      */
@size		int output	/* Estimated size of dump file (return value) */
as
declare	@cache_size	int,
	@proc_percent	int,
	@proc_size	int,
	@defpagecache	int,
	@defproccache	int,
	@memory		int

select @cache_size = 0
select @proc_size = 0

/*
** Determine the default settings for page caches and procedure cache
*/
select @defpagecache = int_value 
	from master.dbo.sysattributes sa
        where sa.class 		= 7
        and sa.object_type 	= "DC"
        and sa.attribute 	= 5
        and sa.object_info1 	= 5
	
select @defproccache = int_value 
	from master.dbo.sysattributes sa
        where sa.class 		= 7
        and sa.object_type 	= "DC"
        and sa.attribute 	= 5
        and sa.object_info1 	= 6

/* 
** Get total size of page caches in kilobytes
** 19 is the config # for named caches 
*/
select @cache_size = sum(cu.value)
	from master.dbo.sysconfigures co, master.dbo.syscurconfigs cu
	where co.config	= 19 
	and co.config 	= cu.config
	and co.name 	= cu.comment

/*
** Obtain the current total memory allocated to the server in kilobytes.
** Since the value stored in sysconfigures in in pages, which are 2 K, 
** multiply by 2 to translate into kilobytes.  104 is the
** configuration # for total memory.
*/
select @memory = cu.value * 2
	from master.dbo.sysconfigures co, master.dbo.syscurconfigs cu
	where co.config 	= 104
	and co.config 		= cu.config

select @size = @memory

/*
** Determine whether and how much memory to exclude for page caches
*/
if (@pagecache = "Omit" or (@pagecache = "Default" and @defpagecache != 1))
begin
	select @size = @size - @cache_size
end

/*
** Determine whether and how much memory to exclude for procedure cache
*/
if (@proccache = "Omit" or (@proccache = "Default" and  @defproccache != 1))
begin
	/* 108 is the config # for procedure cache percentage */
	select @proc_percent 	= cu.value 
		from master.dbo.sysconfigures co, master.dbo.syscurconfigs cu
		where co.config = 108
		and co.config 	= cu.config

	/*
	** Calculate the size of the procedure cache by subtracting
	** memory allocated to page cache and overhead for the page
	** caches from total memory, then divide by procedure cache
	** percentage.
	*/
	select @proc_size 
		= ((@memory - @cache_size - (@cache_size / 20)) 
			* @proc_percent) / 100
	select @size = @size - @proc_size
end

/*
** Translate from kilobytes into megabytes; add 1 to compensate
** for effects of rounding
*/
select @size = @size / 1024 + 1

return 0

go
exec sp_procxmode 'sp_shmdumpsize', 'anymode'
go
grant execute on sp_shmdumpsize to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_shmdumpconfig')
begin
	drop procedure sp_shmdumpconfig
end
go
print "Installing sp_shmdumpconfig"
go

/*
** SP_SHMDUMPCONFIG
**
** This file contains the definition of the sp_dumpconfig system
** stored procedure.  This stored procedure is used to set shared
** memory dump conditions and to display the current dump condition
** settings.  The sa_role is required to make any changes to the
** system configuration, but public access is granted to display the
** current settings.
**
** This stored procedure calls the sp_shmdumpsize stored procedure 
** in order to get size estimates for the shared memory dump files
** that will be generated for each condition.
**
** History:
** 19sept96	pdorfman	Initial coding
** 24jan97	pdorfman	Code nearly complete
*/

create procedure sp_shmdumpconfig
/* -------------- Stored Procedure Parameters ----------------------- */
@action 	varchar(10) = "display",/* action requested by user   */
@type 		varchar(20) 	= "",	/* type of attribute affected */
@value 		int		= NULL,	/* attribute value            */
@maxdumps 	int 		= NULL,	/* maximum # of dumps         */
@dirname	varchar(255)	= NULL,	/* dump directory             */
@filename	varchar(30)	= NULL,	/* dump file name             */
@memarg1	varchar(20)	= NULL,	/* in/exclude memory type     */
@memarg2	varchar(20)	= NULL,	/* in/exclude memory type     */
@memarg3	varchar(20)	= NULL	/* in/exclude memory type     */
as

/* ----------------- Declare Local Variables ------------------------ */
declare @object		int, 		/* object column value        */
	@charvalue 	varchar(255), 	/* charvalue column value     */
	@attrib   	int,		/* attribute column value     */
	@not_status 	int,		/* notification return status */
	@memobject	int,		/* object type for memtype    */
	@curarg		varchar(20),	/* memory mode working var    */
	@memtype	int,		/* type of memory for obj     */
	@memsetting	int,		/* setting for this memtype   */
	@counter	int,		/* counter                    */
	@recfound	int,		/* record already exists      */
	@notify_cnt	int,		/* count notification done    */
	@maxconds	int,		/* max # dump conditions      */
	@curcount	int,		/* current # dump cond's      */
	@header_printed	int,		/* display header printed     */
	@print_str	varchar(255),	/* for printing error msgs    */
	@trancount	int		/* receiver for @@trancount   */

/*
** The following variables are treated as constants within this
** stored procedure. They are set below.
*/
declare @DUMPCOND_CLASS	int,		/* sysattributes class        */
	@OBJTYPE	char(2),	/* sysattributes object typ   */
	@CFG_PRIMARY	int,		/* primary record id          */
	@CFG_FILENAME	int,		/* file name record id        */
	@CFG_DIRNAME	int,		/* directory name record id   */
	@CFG_MAXDUMPS	int,		/* maxdumps record id         */
	@CFG_PAGECACHE	int,		/* page cache record id       */
	@CFG_PROCCACHE	int,		/* proc cache record id       */
	@CFG_UNUSED	int,		/* unused memory record id    */
	@ATTR_ADD	int,		/* add notification value     */
	@ATTR_CHANGE	int,		/* change notification val    */
	@ATTR_DROP	int,		/* drop notification value    */
	@ATTR_FETCH	int,		/* fetch notification value   */
	@CFG_INCLUDE	int,		/* include memory type        */
	@CFG_OMIT	int,		/* omit memory type           */
	@CFG_DEFAULT	int		/* use default mem setting    */

/*
** Declare variables and cursors used to display current settings
*/
declare	@cond_name	char(8),
	@cond_value	int,
	@cond_cvalue	char(5),
	@cond_attrib	int,
	@rectype	int,
	@int_val	int,
	@char_val	varchar(255),
	@cmaxdumps	char(7),
	@cpagecache	varchar(20),
	@cproccache	varchar(20),
	@cunused	varchar(20),
	@cdirname	varchar(255),
	@cfilename	varchar(30),
	@defaults_found	int,
	@dumpsize	int,
	@cdumpsize	varchar(8)

/*
** Create temporary lookup table referenced by the c_conditions
** cursor (below).  Table creation is required here in order to 
** declare the cursor.
*/
create table #attname (attrib int, name char(8))

/*
** Cursor to return all dump condition rows, ordered by object type
** (attribute)
*/
declare c_conditions cursor
	for select an.name, sa.attribute, sa.object
	from master.dbo.sysattributes sa, #attname an
	where sa.class = @DUMPCOND_CLASS
	and sa.object_type = @OBJTYPE
	and sa.attribute = an.attrib
	and sa.object_info1 = @CFG_PRIMARY
	order by sa.attribute

/*
** Cursor to return all settings for a given dump condition
*/
declare c_settings cursor
	for select sa.object_info1, sa.int_value, sa.char_value
	from master.dbo.sysattributes sa
	where sa.class = @DUMPCOND_CLASS
	and sa.object_type = @OBJTYPE
	and sa.attribute = @cond_attrib
	and sa.object = @cond_value
	and sa.object_info1 != @CFG_PRIMARY

/* ----------------- Setup and Validation ------------------------ */
set nocount on

/*
** Class ID and type defined in utils/attrib.lst
*/
select @DUMPCOND_CLASS 	= 7
select @OBJTYPE		= "DC"

/*
** The following constants define record types for the dump condition
** class in the sysattributes table.The values set here must be the 
** same as those defined in utils/cfgdump.c.
*/
select @CFG_PRIMARY 	= 1
select @CFG_FILENAME 	= 2
select @CFG_DIRNAME 	= 3
select @CFG_MAXDUMPS 	= 4
select @CFG_PAGECACHE 	= 5
select @CFG_PROCCACHE 	= 6
select @CFG_UNUSED 	= 7

/*
** The following constants are used or setting memory mode.
** These values must correspond to those used in utils/cfgdump.c.
*/
select @CFG_DEFAULT	= 0
select @CFG_INCLUDE	= 1
select @CFG_OMIT	= 2

/*
** The following must correspond to values in sysattr.h
*/
select @ATTR_ADD 	= 1
select @ATTR_CHANGE	= 2
select @ATTR_DROP	= 3
select @ATTR_FETCH	= 4

select @notify_cnt 	= 0

/*
** Determine the attribute number for the attribute indicated
** by the @type parameter.
**
** NOTE: The integer values used for @attrib here must correspond to values
** defined in utils/attrib.lst.  Any changes made here must also be made
** in attrib.lst, and vice versa.
*/
if @type = 'error'
        select @attrib = 1
else if @type = 'signal'
        select @attrib = 2 
else if @type = 'severity' 
        select @attrib = 3 
else if @type = 'module'  
        select @attrib = 4 
else if @type = 'defaults' 
        select @attrib = 5 
else if @action = 'debug'
begin
	select @action = 'display'
	select @type = 'debug'
end
else if @action != 'display'
begin 
	/*
	** We are here because @type does not have a valid value
	** and the @action value is not 'display'. Since the only action 
	** that does not require an @type value is 'display', raise an
	** error and return.
	*/
        /*
        ** 18492, "Invalid dump condition type %1!"
        */
        exec sp_getmessage 18492, @print_str output
        print @print_str, @type
        return 1
end 
 
/* ----------------- Identify and Perform the Command ----------- */

/*
** Add a new dump condition or configuration parameter
*/
if (@action in ('add', 'update', 'reset'))
begin
	/*
	** Verify that the user has sufficient permissions to
	** update the dump configuration
	*/
	if (proc_role("sa_role") != 1)
	begin
		return 2
	end

	/*
	** Make sure valid parameters were provided
	*/
	if (@action = 'add')
	begin
		if (@type = 'defaults')
		begin
			/*
			** 18493 "You cannot add the system default settings. Use update."
			*/
			exec sp_getmessage 18493, @print_str output
			print @print_str
			return 3
		end

		if (@value = NULL)
		begin
			/*
			** 18494 "No value for %1! was given."
			*/
			exec sp_getmessage 18494, @print_str output
			print @print_str, @type
			print "No value for %1! was given.", @type
			return 4
		end

	end

	/*
	** Determine whether there is room to add another dump condition
	*/
	if (@action = 'add')
	begin
		/*
		** Get configured maximum number of dump conditions
		*/
		select @maxconds = value
			from master.dbo.sysconfigures
			where name = 'maximum dump conditions'

		/*
		** Count number of conditions set for type error, signal or module
		*/
		select @curcount = count(*)
			from master.dbo.sysattributes
			where class = @DUMPCOND_CLASS
			and object_info1 = @CFG_PRIMARY
			and attribute in (1, 2, 3, 4)

		/*
		** Raise an error if there is no more room
		*/
		if (@curcount >= @maxconds)
		begin
			/*
			** RESOLVE: Need an error message here
			*/
			/*
			** 18495, "The maximum number of dump conditions (%1!) are already set."
			*/
			exec sp_getmessage 18495, @print_str output
			print @print_str, @maxconds

			/*
			** 18496,  "Either drop a dump condition or increase the value of 'maximum dump conditions'."
			*/
			exec sp_getmessage 18496, @print_str output
			print @print_str
			return 5
		end
	end
	else if (@action != 'reset')
	begin
		/*
		** Make sure that the user has provided arguments for at
		** least one updatable value.
		*/
		if (@maxdumps = NULL and @dirname = NULL and @filename = NULL 
		    and @memarg1 = NULL and @memarg2 = NULL and @memarg3 = NULL)
		begin
			/*
			** 18497, "No values to update were given."
			*/
			exec sp_getmessage 18497, @print_str output
			print @print_str
			return 6
		end
	end
	 
	select @object = @value

	/*
	** Determine whether there are currently any records for the
	** the conditions supplied by the user.  This information is
	** used below.
	*/
	if (@type in ('severity', 'defaults'))
	begin
		if exists (select * from master.dbo.sysattributes
				where class = @DUMPCOND_CLASS
				and attribute = @attrib)
		begin
			select @recfound = 1
		end
		else
		begin
			select @recfound = 0
		end
	end
	else
	begin
		if exists (select * from master.dbo.sysattributes
				where class = @DUMPCOND_CLASS
				and attribute = @attrib
				and object = @object)
		begin
			select @recfound = 1
		end
		else
		begin
			select @recfound = 0
		end
	end

	/*
	** Determine whether action can proceed.  For add, record must
	** not already exist, for update it must exist.
	*/
	if (@action = 'add' and @recfound = 1)
	begin
		if (@type in ('severity', 'defaults'))
		begin
			/*
			** 18498, "There is already a condition of type %1!"
			*/
			exec sp_getmessage 18498, @print_str output
			print @print_str, @type
		end
		else
		begin
			/*
			** 18499, "There is already a condition of type %1! and value %2!"
			*/
			exec sp_getmessage 18499, @print_str output
			print @print_str, @type, @value
		end
		return 7
	end
	else if (@action = 'update' and @recfound = 0 and @type != 'defaults')
	begin
		if (@type in ('severity', 'defaults'))
		begin
			/*
			** 18500, "No record found for %1!"
			*/
			exec sp_getmessage 18500, @print_str output
			print @print_str, @type
		end
		else
		begin
			/*
			** 18501, "No record found for %1! %2!"
			*/
			exec sp_getmessage 18501, @print_str output
			print @print_str, @type, @value
		end
		return 8
	end

	/*
	** Validate the dump condition. Signal value cannot be
	** verified, since this is determined by the operating
	** system.
	*/
	if (@type = 'error')
	begin
		/*
		** Verify that an row exists for this error number
		** in the master..sysmessages table
		*/
		if not exists (select * from master..sysmessages
					where error = @value)
		begin
			/*
			** 18502, "%1! is not a valid error number"
			*/
			exec sp_getmessage 18502, @print_str output
			print @print_str, @value
			return 9
		end
	end
	else if (@type = 'module')
	begin
		/*
		** Make sure there is at least one error in
		** master..sysmessages that belongs to this module
		*/
		if ((@value % 100 != 0)
		    or not exists (select * from master..sysmessages
					where error between @value
					and @value + 99))
		begin
			/*
			** 18503, "%1! is not a valid module"
			*/
			exec sp_getmessage 18503, @print_str output
			print @print_str, @value
			return 10
		end
	end
	else if (@type = 'severity')
	begin
		/*
		** Minimum severity = 10; maximum severity = 26
		*/
		if (@value < 10 or @value > 26)
		begin
			/*
		`	** 18504, "Severity must be between 10 and 26"
			*/
			exec sp_getmessage 18504, @print_str output
			print @print_str
			return 11
		end

		/*
		** Make sure we have the correct severity value
		*/
		if (@action = 'update')
		begin
			select @object = object
				from master.dbo.sysattributes
				where class = @DUMPCOND_CLASS
				and attribute = @attrib
		end
	end
	else if (@type = 'defaults')
	begin
		if (@value != null)
		begin
			/*
			** 18536, "The value parameter must be NULL when setting system defaults."
			*/
			exec sp_getmessage 18536, @print_str output
			print @print_str
			goto error_exit
		end

		/*
		** If there is not a default record, add one.
		*/
		if (@recfound = 0)
		begin
			select @action = 'add'
		end
	end

	/*
	** Reset the dump count for this condition.  This does not require
	** updating the sysattributes table, but a call must be made to
	** attrib_notify() to reset the value.
	*/
	if (@action = 'reset')
	begin
		if (@type = 'defaults')
		begin
			/*
			** 18518,  "You cannot reset the dump count for the default setting."
			*/
			exec sp_getmessage 18518, @print_str output
			print @print_str
			return 12
		end

		/*
		** A non-zero value for info2 for the maxdumps entry
		** indicates that the dump count should be reset.
		*/
		select @not_status 
			= attrib_notify(@DUMPCOND_CLASS,/*cl*/
				@attrib, 	/*attrib */
				@OBJTYPE,    	/*type*/ 
				@object, 	/*object*/
				@CFG_MAXDUMPS,	/*info1*/
				1, 		/*info2*/
				NULL, 		/*info3*/
				NULL, 		/*cinfo*/
				NULL,		/*intval*/
				NULL, 		/*charval*/
				NULL, 		/*textval*/
				NULL, 		/*imageval*/
				NULL,		/*comment*/
				@ATTR_CHANGE)

		if (@not_status = 0)
		begin
			/*
			** 18505, "Notification failed. Condition not set."
			*/
			exec sp_getmessage 18505, @print_str output
			print @print_str
			return 13
		end

		/*
		** 18517, "Dump count reset for %1! %2!"
		*/
		exec sp_getmessage 18517, @print_str output
		print @print_str, @type, @value
		return 0
	end

	/*
	** Values have been validated. Begin transaction and
	** insert primary row if needed.
	*/
	begin tran add_condition

	/*
	** For add action, the primary record must first be added. For
	** update, it already exists.
	*/
	if (@action = 'add')
	begin
		/*
		** Insert primary record for new entry in sysattributes 
		** table and invoke the notification routine if insert 
		** is successful.
		*/
		insert master.dbo.sysattributes
			(class, attribute, object_type, object, object_info1)
			values (@DUMPCOND_CLASS, @attrib, @OBJTYPE, @object,
					@CFG_PRIMARY)

		if (@@error = 0)
		begin
			select @not_status = attrib_notify(@DUMPCOND_CLASS, 
						@attrib, @OBJTYPE, 
						@object, @CFG_PRIMARY,
						NULL, NULL, NULL, NULL,
						NULL, NULL, NULL, NULL,
						@ATTR_ADD)

			if (@not_status = 0)
			begin
				/*
				** 18505, "Notification failed. Condition not set."
				*/
				exec sp_getmessage 18505, @print_str output
				print @print_str
				goto error_exit
			end

			select @notify_cnt = @notify_cnt + 1
		end
		else
		begin
			/*
			** 18506, "Insert of new record for %1! %2 failed."
			*/
			exec sp_getmessage 18506, @print_str output
			print @print_str, @type, @value
			goto error_exit
		end
	end

	/*
	** Now insert rows for any additional condition settings
	** that were specified by the user.
	*/
	if (@maxdumps != NULL)
	begin
		if (@maxdumps <= 0)
		begin
			/*
			** 18519, "The maxdumps parameter value must be greater than zero."
			*/
			exec sp_getmessage 18519, @print_str output
			print @print_str
			goto error_exit
		end

		/*
		** A value of 0 means that the existing maxdumps setting
		** for this condition is being dropped. The sysattributes
		** row is removed and attrib_notify() is called to unset
		** the maxdumps value internally.
		*/
		/*
		** Delete existing entry, if there is one
		*/
		if (@action = 'update'
		    and exists (select * from master.dbo.sysattributes
			where class = @DUMPCOND_CLASS
			and attribute = @attrib
			and object_type = @OBJTYPE
			and object = @object
			and object_info1 = @CFG_MAXDUMPS))
		begin
			delete master.dbo.sysattributes
				where class = @DUMPCOND_CLASS
				and attribute = @attrib
				and object_type = @OBJTYPE
				and object = @object
				and object_info1 = @CFG_MAXDUMPS
		end

		if (@maxdumps != 0)
		begin
			insert master.dbo.sysattributes
				(class, attribute, object_type, object, 
					object_info1, int_value)
				values(@DUMPCOND_CLASS, @attrib, @OBJTYPE, 
					@object, @CFG_MAXDUMPS, @maxdumps)
		end

		if (@@error = 0)
		begin
			/*
			** info2 must be set to zero to indicate the
			** the maxdumps value should be updated.
			*/
			select @not_status 
				= attrib_notify(@DUMPCOND_CLASS,/*cl*/
					@attrib, 	/*attrib */
					@OBJTYPE,    	/*type*/ 
					@object, 	/*object*/
					@CFG_MAXDUMPS,	/*info1*/
					0, 		/*info2*/
					NULL, 		/*info3*/
					NULL, 		/*cinfo*/
					@maxdumps,	/*intval*/
					NULL, 		/*charval*/
					NULL, 		/*textval*/
					NULL, 		/*imageval*/
					NULL,		/*comment*/
					@ATTR_CHANGE)

			if (@not_status = 0)
			begin
				/*
				** 18505, "Notification failed. Condition not set."
				*/
				exec sp_getmessage 18505, @print_str output
				print @print_str
				goto error_exit
			end

			select @notify_cnt = @notify_cnt + 1
		end
		else
		begin
			goto error_exit
		end
	end

	/*
	** Set dump directory name if specified.  If user supplies a
	** @dirname value of "", drop the current value.
	*/
	if (@dirname != NULL) 
	begin
		/*
		** Delete existing entry, if there is one
		*/
		if (@action = 'update'
		    and exists (select * from master.dbo.sysattributes
			where class = @DUMPCOND_CLASS
			and attribute = @attrib
			and object_type = @OBJTYPE
			and object = @object
			and object_info1 = @CFG_DIRNAME))
		begin
			delete master.dbo.sysattributes
				where class = @DUMPCOND_CLASS
				and attribute = @attrib
				and object_type = @OBJTYPE
				and object = @object
				and object_info1 = @CFG_DIRNAME
		end

		/*
		** If user supplies a @dirname value of "", then just
		** drop the current setting but do not insert a new one.
		*/
		if (@dirname != "")
		begin
			insert master.dbo.sysattributes
				(class, attribute, object_type, object, 
					object_info1, char_value)
				values(@DUMPCOND_CLASS, @attrib, @OBJTYPE, 
					@object, @CFG_DIRNAME, @dirname)

			if (@@error = 0)
			begin
				select @not_status 
					= attrib_notify(@DUMPCOND_CLASS,/*cl*/
						@attrib, 	/*attrib*/
						@OBJTYPE,    	/*type*/ 
						@object, 	/*object*/
						@CFG_DIRNAME,	/*info1*/
						NULL, 		/*info2*/
						NULL, 		/*info3*/
						NULL, 		/*cinfo*/
						NULL,		/*intval*/
						@dirname, 	/*charval*/
						NULL, 		/*textval*/
						NULL, 		/*imageval*/
						NULL,		/*comment*/
						@ATTR_CHANGE)

				if (@not_status = 0)
				begin
					/*
					** 18505, "Notification failed. Condition not set."
					*/
					exec sp_getmessage 18505, 
							@print_str output
					print @print_str
					goto error_exit
				end

				select @notify_cnt = @notify_cnt + 1
			end
			else
			begin
				goto error_exit
			end
		end
		else
		begin
			/*
			** Drop the dump directory entry for this
			** condition.
			*/
			if (@@error = 0)
			begin
				select @not_status 
					= attrib_notify(@DUMPCOND_CLASS,/*cl*/
						@attrib, 	/*attrib*/
						@OBJTYPE,    	/*type*/ 
						@object, 	/*object*/
						@CFG_DIRNAME,	/*info1*/
						NULL, 		/*info2*/
						NULL, 		/*info3*/
						NULL, 		/*cinfo*/
						NULL,		/*intval*/
						NULL,	 	/*charval*/
						NULL, 		/*textval*/
						NULL, 		/*imageval*/
						NULL,		/*comment*/
						@ATTR_DROP)

				if (@not_status = 0)
				begin
					/*
					** 18505, "Notification failed. Condition not set."
					*/
					exec sp_getmessage 18505,
							 @print_str output
					print @print_str
					goto error_exit
				end
				select @notify_cnt = @notify_cnt + 1
			end
			else
			begin
				goto error_exit
			end
		end
	end

	/*
	** Set dump file name if specified. Drop the current value if
	** the user supplies a @filename value of "".
	*/
	if (@filename != NULL) 
	begin
		/*
		** Delete existing entry, if there is one
		*/
		if (@action = 'update'
		    and exists (select * from master.dbo.sysattributes
			where class = @DUMPCOND_CLASS
			and attribute = @attrib
			and object_type = @OBJTYPE
			and object = @object
			and object_info1 = @CFG_FILENAME))
		begin
			delete master.dbo.sysattributes
				where class = @DUMPCOND_CLASS
				and attribute = @attrib
				and object_type = @OBJTYPE
				and object = @object
				and object_info1 = @CFG_FILENAME
		end

		/*
		** If the user supplies a @filename value of "", drop
		** the current value but do not insert a new one.
		*/
		if (@filename != "")
		begin
			insert master.dbo.sysattributes
				(class, attribute, object_type, object, 
					object_info1, char_value)
				values(@DUMPCOND_CLASS, @attrib, @OBJTYPE, 
					@object, @CFG_FILENAME, @filename)

			if (@@error = 0)
			begin
				select @not_status 
					= attrib_notify(@DUMPCOND_CLASS,/*cl*/
						@attrib, 	/*attrib */
						@OBJTYPE,    	/*type*/ 
						@object, 	/*object*/
						@CFG_FILENAME,	/*info1*/
						NULL, 		/*info2*/
						NULL, 		/*info3*/
						NULL, 		/*cinfo*/
						NULL,		/*intval*/
						@filename,	/*charval*/
						NULL, 		/*textval*/
						NULL, 		/*imageval*/
						NULL,		/*comment*/
						@ATTR_CHANGE)

				if (@not_status = 0)
				begin
					/*
					** 18505, "Notification failed. Condition not set."
					*/
					exec sp_getmessage 18505, 
							@print_str output
					print @print_str
					goto error_exit
				end
				select @notify_cnt = @notify_cnt + 1
			end
			else
			begin
				goto error_exit
			end
		end
		else
		begin
			/*
			** Drop the dump file name entry for this
			** condition.
			*/
			if (@@error = 0)
			begin
				select @not_status 
					= attrib_notify(@DUMPCOND_CLASS,/*cl*/
						@attrib, 	/*attrib*/
						@OBJTYPE,    	/*type*/ 
						@object, 	/*object*/
						@CFG_FILENAME,	/*info1*/
						NULL, 		/*info2*/
						NULL, 		/*info3*/
						NULL, 		/*cinfo*/
						NULL,		/*intval*/
						NULL,	 	/*charval*/
						NULL, 		/*textval*/
						NULL, 		/*imageval*/
						NULL,		/*comment*/
						@ATTR_DROP)

				if (@not_status = 0)
				begin
					/*
					** 18505, "Notification failed. Condition not set."
					*/
					exec sp_getmessage 18505, 
							@print_str output
					print @print_str
					goto error_exit
				end
				select @notify_cnt = @notify_cnt + 1
			end
			else
			begin
				goto error_exit
			end
		end
	end

	if (@memarg1 != NULL or @memarg2 != NULL or @memarg3 !=NULL) 
	begin
		select @counter = 0
		while (@counter < 3)
		begin
			/*
			** Set @curarg to current argument's value
			*/
			if (@counter = 0)
				select @curarg = @memarg1
			else if (@counter = 1)
				select @curarg = @memarg2
			else if (@counter = 2)
				select @curarg = @memarg3

			/*
			** If arg is unset, go to next one
			*/
			if (@curarg = NULL)
			begin
				select @counter = @counter + 1
				continue
			end

			/*
			** Determine settings based on user's input
			*/
			if (@curarg = "include_page")
			begin
				select @memtype = @CFG_PAGECACHE
				select @memsetting = @CFG_INCLUDE
			end
			else if (@curarg = "omit_page")
			begin
				select @memtype = @CFG_PAGECACHE
				select @memsetting = @CFG_OMIT
			end
			else if (@curarg = "default_page")
			begin
				select @memtype = @CFG_PAGECACHE
				select @memsetting = @CFG_DEFAULT
			end
			else if (@curarg = "include_proc")
			begin
				select @memtype = @CFG_PROCCACHE
				select @memsetting = @CFG_INCLUDE
			end
			else if (@curarg = "omit_proc")
			begin
				select @memtype = @CFG_PROCCACHE
				select @memsetting = @CFG_OMIT
			end
			else if (@curarg = "default_proc")
			begin
				select @memtype = @CFG_PROCCACHE
				select @memsetting = @CFG_DEFAULT
			end
			else if (@curarg = "include_unused")
			begin
				select @memtype = @CFG_UNUSED
				select @memsetting = @CFG_INCLUDE
			end
			else if (@curarg = "omit_unused")
			begin
				select @memtype = @CFG_UNUSED
				select @memsetting = @CFG_OMIT
			end
			else if (@curarg = "default_unused")
			begin
				select @memtype = @CFG_UNUSED
				select @memsetting = @CFG_DEFAULT
			end
			else
			begin
				/*
				** RESOLVE: Need message here
				*/
				/*
				** 18507, "Invalid memory mode %1!"
				*/
				exec sp_getmessage 18507, @print_str output
				print @print_str, @curarg
				goto error_exit
			end

			/*
			** Delete existing entry, if there is one
			*/
			if (@action = 'update'
			    and exists (select * from master.dbo.sysattributes
				where class = @DUMPCOND_CLASS
				and attribute = @attrib
				and object_type = @OBJTYPE
				and object = @object
				and object_info1 = @memtype))
			begin
				delete master.dbo.sysattributes
					where class = @DUMPCOND_CLASS
					and attribute = @attrib
					and object_type = @OBJTYPE
					and object = @object
					and object_info1 = @memtype
			end

			/*
			** There is no need to insert a row to set
			** memory setting to default. Any previous
			** row should be deleted and the notification
			** function must be called.
			*/
			if (@memsetting != @CFG_DEFAULT)
			begin
				/*
				** Insert row into sysattributes table
				*/
				insert master.dbo.sysattributes
					(class, attribute, object_type, 
						object, object_info1, 
						int_value)
					values(@DUMPCOND_CLASS, @attrib, 
						@OBJTYPE, @object, @memtype,
						@memsetting)

				if (@@error = 0)
				begin
					select @not_status 
						= attrib_notify(
							@DUMPCOND_CLASS,/*cl*/
							@attrib,/*attrib */
							@OBJTYPE,/*type*/ 
							@object,/*object*/
							@memtype,/*info1*/
							NULL, 	/*info2*/
							NULL, 	/*info3*/
							NULL, 	/*cinfo*/
							@memsetting,/*intval*/
							NULL,	/*charval*/
							NULL, 	/*textval*/
							NULL, 	/*imageval*/
							NULL,	/*comment*/
							@ATTR_CHANGE)

					if (@not_status = 0)
					begin
						/*
						** 18505, "Notification failed. Condition not set."
						*/
						exec sp_getmessage 18505, 
							@print_str output
						print @print_str
						goto error_exit
					end
					select @notify_cnt = @notify_cnt + 1
				end
				else
				begin
					goto error_exit
				end
			end
			else
			begin
				/*
				** Drop this memory setting for this
				** condition.
				*/
				if (@@error = 0)
				begin
					select @not_status 
						= attrib_notify(
							@DUMPCOND_CLASS,/*cl*/
							@attrib,/*attrib */
							@OBJTYPE,/*type*/ 
							@object,/*object*/
							@memtype,/*info1*/
							NULL, 	/*info2*/
							NULL, 	/*info3*/
							NULL, 	/*cinfo*/
							NULL,	/*intval*/
							NULL,	/*charval*/
							NULL, 	/*textval*/
							NULL, 	/*imageval*/
							NULL,	/*comment*/
							@ATTR_DROP)

					if (@not_status = 0)
					begin
						/*
						** 18505, "Notification failed. Condition not set."
						*/
						exec sp_getmessage 18505, 
							@print_str output
						print @print_str
						goto error_exit
					end
					select @notify_cnt = @notify_cnt + 1
				end
				else
				begin
					goto error_exit
				end
			end

			select @counter = @counter + 1
		end
	end

	/*
	** All rows successfully added for this condition.
	** Commit transaction.
	*/
	commit tran add_condition
end
/*
** Drop a dump condition
*/
else if (@action = 'drop')
begin
	/*
	** Verify that the user has sufficient permissions to
	** update the dump configuration
	*/
	if (proc_role("sa_role") != 1)
	begin
		return 14
	end

	if (@type = 'defaults')
	begin
		/*
		** 18508, "You cannot drop the system default settings"
		*/
		exec sp_getmessage 18508, @print_str output
		print @print_str
		return 15
	end
	 
	begin tran drop_condition

	/*
	** Delete all rows belonging to this condition from
	** the sysattributes table.
	*/
	if (@type = 'severity' and @value = NULL)
	begin
		/*
		** Value not required in order to drop
		** a severity condition
		*/
		delete master.dbo.sysattributes
			where class = @DUMPCOND_CLASS    
			and object_type = @OBJTYPE   
			and attribute = @attrib 
	end
	else if (@type = 'defaults' and @value = NULL)
	begin
		/*
		** Value not required in order to drop
		** default condition
		*/
		delete master.dbo.sysattributes
			where class = @DUMPCOND_CLASS    
			and object_type = @OBJTYPE   
			and attribute = @attrib 
	end
	else
	begin
		/*
		** For other condition types a value
		** must also be supplied.
		*/
		select @object = @value
		delete master.dbo.sysattributes
			where class = @DUMPCOND_CLASS    
			and object_type = @OBJTYPE   
			and attribute = @attrib 
			and object = @object
	end

	if (@@rowcount = 0)
	begin
		/*
		** 18509, "There is no condition set for %1! %2!"
		*/
		exec sp_getmessage 18509, @print_str output
		print @print_str, @type, @object
		rollback tran drop_condition
		return 19
	end

	if (@@error = 0)
	begin
		select @not_status = attrib_notify(
					@DUMPCOND_CLASS,/*cl*/
					@attrib, 	/*attrib */
					@OBJTYPE,    	/*type*/ 
					@object, 	/*object*/
					@CFG_PRIMARY,	/*info1*/
					NULL, 		/*info2*/
					NULL, 		/*info3*/
					NULL, 		/*cinfo*/
					NULL,		/*intval*/
					NULL,		/*charval*/
					NULL, 		/*textval*/
					NULL, 		/*imageval*/
					NULL,		/*comment*/
					@ATTR_DROP)

		if (@not_status = 0)
		begin
			/*
			** 18510, "Notification failed. Your change did not take affect."
			*/
			exec sp_getmessage 18510, @print_str output
			print @print_str
			rollback tran drop_condition
			return 20
		end
	end

	/*
	** Delete of rows and notification were successful.
	** Commit transaction.
	*/
	commit tran drop_condition
end
/*
** Display current dump condition configuration
*/
else if (@action = 'display')
begin
	create table #conditions
		(Type		char(8),
		 Value		char(5),
		 Maxdumps	char(7),
		 Page_Cache	char(7),
		 Proc_Cache	char(7),
		 Unused_Space	char(7),
		 Est_File_Size	varchar(8),
		 Filename	varchar(30),
		 Directory	varchar(255))

	select @defaults_found = 0
	select @header_printed = 0

	/*
	** Create table #attname (attrib int, name char(25))
	** NOTE: The atribute values must correspond to those defined
	** in utils/attrib.lst.
	*/
	insert #attname values (1, 'Error   ')
	insert #attname values (2, 'Signal  ')
	insert #attname values (3, 'Severity')
	insert #attname values (4, 'Module  ')
	insert #attname values (5, 'Defaults')

	/*
	** Open curson to select all dump conditions
	*/
	open c_conditions

	fetch c_conditions into @cond_name, @cond_attrib, @cond_value

	if (@@sqlstatus = 1)
	begin
		/*
		** 18511, "Error reading sysattributes table"
		*/
		exec sp_getmessage 18511, @print_str output
		print @print_str
		return 16
	end

	select @cmaxdumps 	= "Default"
	select @cpagecache 	= "Default"
	select @cproccache 	= "Default"
	select @cunused 	= "Default"
	select @cfilename	= "Default File Name"
	select @cdirname	= "Default Directory"

	while (@@sqlstatus = 0)
	begin

		/*
		** Fetch all special settings for the current
		** dump condition
		*/
		open c_settings

		fetch c_settings into @rectype, @int_val, @char_val

		while (@@sqlstatus = 0)
		begin
			if (@rectype = @CFG_MAXDUMPS)
			begin
				select @cmaxdumps = convert(char(7), @int_val)
			end
			else if (@rectype = @CFG_PAGECACHE)
			begin
				if (@int_val = 1)
					select @cpagecache = 'Include'
				else
					select @cpagecache = 'Omit   '
			end
			else if (@rectype = @CFG_PROCCACHE)
			begin
				if (@int_val = 1)
					select @cproccache = 'Include'
				else
					select @cproccache = 'Omit   '
			end
			else if (@rectype = @CFG_UNUSED)
			begin
				if (@int_val = 1)
					select @cunused = 'Include'
				else
					select @cunused = 'Omit   '
			end
			else if (@rectype = @CFG_DIRNAME)
			begin
				select @cdirname = @char_val
			end
			else if (@rectype = @CFG_FILENAME)
			begin
				select @cfilename = @char_val
			end
			else
			begin
				/*
				** 18512, "WARNING: Unknown dump condition record type found: %1!"
				*/
				exec sp_getmessage 18512, @print_str output
				print @print_str, @rectype
			end

			fetch c_settings 
				into @rectype, @int_val, @char_val
		end /* while (@@sqlstatus = 0) */

		/*
		** Close cursor on settings for current condition
		*/
		close c_settings

		select @cond_cvalue = convert(char(5), @cond_value)

		/*
		** Handle the system default settings separately.
		*/
		if (@cond_attrib = 5)
		begin
display_defaults:
			select @defaults_found = 1

			if (@header_printed = 1)
			begin
				print " "
			end

			/*
			** The value column is not applicable to the
			** system defaults setting
			*/
			select @cond_cvalue = '---  '

			/*
			** If the following values are not set by
			** records in the sysattributes table, report
			** the built in system defaults that we know will
			** be enforced at dump time (csmd_dump_condition)
			** using values hard-coded in the software.
			*/
			if (@cmaxdumps = 'Default')
			begin
				select @cmaxdumps = '1      '
			end

			if (@cpagecache = 'Default')
			begin
				select @cpagecache = 'Omit   '
			end

			if (@cproccache = 'Default')
			begin
				select @cproccache = 'Omit   '
			end

			if (@cunused = 'Default')
			begin
				select @cunused = 'Omit   '
			end

			if (@cfilename = 'Default File Name')
			begin
				select @cfilename = 'Generated File Name'
			end

			if (@cdirname = 'Default Directory')
			begin
				select @cdirname = '$SYBASE'
			end
		end /* (@cond_attrib = 5) */

		/*
		** Calculate the estimated dump file size
		*/
		exec sp_shmdumpsize @cpagecache, @cproccache, @dumpsize output

		/*
		** Convert @dumpsize to varchar and append the units specification to
		** the string
		*/
		select @cdumpsize = (convert(varchar(5), @dumpsize) + " " + "MB")

		/*
		** Insert data for curent condition into worktable for
		** display later.
		*/
		insert #conditions 
			values (@cond_name,
				@cond_cvalue,
				@cmaxdumps,
				@cpagecache,
				@cproccache,
				@cunused,
				@cdumpsize,
				@cfilename,
				@cdirname)

		/*
		** Fetch next dump condition
		*/
		fetch c_conditions into @cond_name, @cond_attrib, @cond_value

		/*
		** Set to default values
		*/
		select @cmaxdumps 	= "Default"
		select @cpagecache 	= "Default"
		select @cproccache 	= "Default"
		select @cunused 	= "Default"
		select @cfilename	= "Default File Name"
		select @cdirname	= "Default Directory"
	end /* while (@@sqlstatus = 0) */

	/*
	** If we didn't find a defaults record, go back and display default
	** values anyway. This is as bit of a kludge, but it will work as long
	** as the goto statement is executed before the close cursor
	** statement that follows.
	*/
	if (@defaults_found = 0)
	begin
		/*
		** There is no entry for the default settings in the
		** sysattributes table.  Display the system defaults 
		** that are defined in the server.
		*/
		select @cond_name 	= 'Defaults'
		select @cmaxdumps 	= '      1'
		select @cdirname	= "$SYBASE"
		goto display_defaults
	end

	/*
	** Close cursor on dump conditions
	*/
	close c_conditions

	select * from #conditions

	/*
	** Get configured maximum number of dump conditions
	*/
	select @maxconds = value
		from master.dbo.sysconfigures
		where name = 'maximum dump conditions'

	/*
	** Subtract 1 so that we don't count the defaults record
	*/
	select @curcount = (count(*) - 1) 
		from #conditions

	/*
	** 18513, "Current number of conditions: %1!"
	*/
	exec sp_getmessage 18513, @print_str output
	print @print_str, @curcount
	/*
	** 18514, "Maximum number of conditions: %1!"
	*/
	exec sp_getmessage 18514, @print_str output
	print @print_str, @maxconds

	if (@type = 'debug')
	begin
		print " "
		exec sp_getmessage 18515, @print_str output
		print @print_str
		print " "
		select @not_status = attrib_notify(@DUMPCOND_CLASS, 1, @OBJTYPE,
						1, NULL,
						NULL, NULL, NULL, NULL,
						NULL, NULL, NULL, NULL,
						@ATTR_FETCH)
	end
end
/*
** An invalid action name has been entered by the user.
*/
else
begin
	/*
	** 18516, "Invalid action %1!"
	*/
	exec sp_getmessage 18516, @print_str output
	print @print_str, @action
        return  17
end

/*
** Indicate success
*/
return 0

/*
** An error occured while inserting rows into the sysattributes table.
** Check to see whether this was an add operation.  If so, remove any in-memory 
** entries added before error occured.  There is a possibility that the
** in-memory data structure will be left in a state that is not consistent
** with the sysattributes table entries.  This would be the case if we were
** performing an update of an existing dump condition and one or more
** rows had been successfully added to sysattributes before the failure
** occured.  In that case, the in-memory table would also have been updated.
** These updates are not transactional and we have no way of restoring them
** to their state prior to the execution of the stored procedure. This
** will only happen in the case of an update operation.  In the case of an 
** add operation, the in-memory entries will be removed by the call to
** attrib_notify() below. To correct this problem, drop and re-add the
** dump condition.
*/
error_exit:

	if (@action = 'add' and @notify_cnt > 0)
	begin
		/*
		** An error occured while adding a new dump
		** condition but the runtime has already been notified.
		** Remove the reference to this condition before
		** returning.
		*/
		select @not_status = attrib_notify(
				@DUMPCOND_CLASS,/*class*/
				@attrib,	/*attrib */
				@OBJTYPE,   	/*type*/ 
				@object,	/*object*/
				@CFG_PRIMARY,	/*info1*/
				NULL, 		/*info2*/
				NULL, 		/*info3*/
				NULL, 		/*cinfo*/
				NULL,		/*intval*/
				NULL,		/*charval*/
				NULL, 		/*textval*/
				NULL, 		/*imageval*/
				NULL,		/*comment*/
				@ATTR_DROP)

		if (@not_status = 0)
		begin
			/*
			** 18505, "Notification failed. Condition not set."
			*/
			exec sp_getmessage 18505, @print_str output
			print @print_str
		end
	end

	/*
	** Rollback any active transaction to undo changes
	** made to the sysattributes table.
	*/
	select @trancount = @@trancount

	if (@trancount > 0)
	begin
		/*
		** Rollback the current transaction
		*/
		rollback tran add_condition
	end

	return 18

/* End of stored procedure */
go
exec sp_procxmode 'sp_shmdumpconfig', 'anymode'
go
grant execute on sp_shmdumpconfig to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_start_xact')
begin
	drop procedure sp_start_xact
end
go
print "Installing sp_start_xact"
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_commit_xact')
begin
	drop procedure sp_commit_xact
end
go
print "Installing sp_commit_xact"
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_abort_xact')
begin
	drop procedure sp_abort_xact
end
go
print "Installing sp_abort_xact"
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_remove_xact')
begin
	drop procedure sp_remove_xact
end
go
print "Installing sp_remove_xact"
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_stat_xact')
begin
	drop procedure sp_stat_xact
end
go
print "Installing sp_stat_xact"
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_probe_xact')
begin
	drop procedure sp_probe_xact
end
go
print "Installing sp_probe_xact"
go

if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_scan_xact')
begin
	drop procedure sp_scan_xact
end
go
print "Installing sp_scan_xact"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/commit */

/*
** Messages for "commit service"        17380
**
** Note: these were Raiserror messages 30000, 30001, 30002
**
** 17380, "Commit service xact id doesn't exist."
*/
 
use master
go

if exists (select *
		from sysobjects
			where name = "spt_committab"
				and sysstat & 7 = 3)
begin
	drop table spt_committab
end
go

CREATE TABLE	spt_committab
(
	commid	int, /* id used to refer to transaction */
	suid	smallint, /* Server Login id of user that starts xa tran
			  ** branch.  This is only used by the XA interface. 
		     	  */
	start	datetime, /* time transaction started */
	lastchange datetime, /* last time this row was updated */
	totnum	smallint, /* number of servers 
			  ** initially involved in xact 
			  */
	outnum	smallint, /* number of servers 
			  ** who still have not completed 
			  */
	heur	char(1), /* 'y'- was heuristically completed */ 
	status	char(1), /* 'a'- abort, 
			    'c'- commit, 
			    'b'- begin, 
			    'p' - prepare */
	xid	 binary(140),	/* tran branch name */
	applname varchar(30), /* application name */
	xactname varchar(30), /* transaction name */
	password varchar(30) NULL /* password protection for updating */
) on system
go
create unique clustered index commitclust on spt_committab(commid) on system
go

use sybsystemprocs
go

if exists (select *
		from sysobjects
			where name = "sp_start_xact")
begin
	drop procedure sp_start_xact
end
go
create procedure sp_start_xact 
	@applname varchar(30),
	@xactname varchar(30),
	@count	smallint,
	@password varchar(30) = NULL
AS

declare 	@xid	  binary(140)

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

set nocount on

BEGIN
	BEGIN TRANSACTION
		select @xid = convert(binary(140), 0x0)

		INSERT master.dbo.spt_committab VALUES 
		(
                        0,
			-1, /* this tells us that this is a non-XA 2pc */
                        getdate(),
                        getdate(),
			@count, 
			@count, 
			'n',
			'b',
			@xid,
			@applname, 
			@xactname,
			@password
		) 

                UPDATE master.dbo.spt_committab
                        set commid = 1 + (select max(commid) from master.dbo.spt_committab)
                        where commid = 0

                SELECT max(commid) from master.dbo.spt_committab
	COMMIT TRANSACTION
END
go

if exists (select *
		from sysobjects
			where name = "sp_commit_xact")
begin
	drop procedure sp_commit_xact
end
go
create procedure sp_commit_xact
	@commid	int,
	@password varchar(30) = NULL
AS

declare @msg varchar(250)

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

if exists (select *
	from master.dbo.spt_committab
	where commid = @commid
	and password = @password)
begin
	/*
	**  If status is aborted, return a 1 to indicate a failure.
	*/
	if exists (select *
			from master.dbo.spt_committab
				where commid = @commid
					and status = 'a')
	begin
		select 1
		return (1)
	end

	/*  Mark the xact as committed. */
	UPDATE master.dbo.spt_committab 
		SET status = 'c', lastchange = getdate()
		WHERE commid = @commid
	select 0
	return (0)
end
else
begin
	/* Error so return 1 */
	/*
	** 17380, "Commit service xact id doesn't exist."
	*/
	exec sp_getmessage 17380, @msg output
	raiserror 30000 @msg
	select 1
	return (1)
end
go

if exists (select *
		from sysobjects
			where name = "sp_abort_xact")
begin
	drop procedure sp_abort_xact
end
go
CREATE PROCEDURE sp_abort_xact
	@commid	int,
	@password varchar(30) = NULL
AS

declare @msg varchar(250)

if exists (select *
	from master.dbo.spt_committab
	where commid = @commid
	and password = @password)
begin
	UPDATE master.dbo.spt_committab 
		SET status = 'a' , lastchange = getdate()
		WHERE commid = @commid
END
else
begin
	/*
	** 17380, "Commit service xact id doesn't exist."
	*/
	exec sp_getmessage 17380, @msg output
	raiserror 30001 @msg
end
go

if exists (select *
		from sysobjects
			where name = "sp_remove_xact")
begin
	drop procedure sp_remove_xact
end
go
CREATE PROCEDURE sp_remove_xact
	@commid	int,
	@count	smallint,
	@password varchar(30) = NULL
AS

declare @msg varchar(250)

if exists (select *
	from master.dbo.spt_committab
	where commid = @commid
	and password = @password)
begin
	/*
	** Decrement outnum by @count.
	*/
	UPDATE master.dbo.spt_committab 
		SET outnum = outnum - @count, lastchange = GETDATE()
		WHERE commid = @commid

	/*
	**  Delete the row if outnum < 1
	*/
	DELETE master.dbo.spt_committab
		WHERE commid = @commid
			and outnum < 1

end
else
begin
	/*
	** 17380, "Commit service xact id doesn't exist."
	*/
	exec sp_getmessage 17380, @msg output
	raiserror 30002 @msg
end
go

if exists (select *
		from sysobjects
			where name = "sp_stat_xact")
begin
	drop procedure sp_stat_xact
end
go
create procedure sp_stat_xact
	@commid	int
AS
BEGIN
	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	IF EXISTS 
	(
		SELECT status 
			FROM master.dbo.spt_committab
			WHERE commid = @commid
	)
		SELECT status 
			FROM master.dbo.spt_committab
			WHERE commid = @commid
	ELSE
		SELECT status = 'u'
END
go

if exists (select *
		from sysobjects
			where name = "sp_probe_xact")
begin
	drop procedure sp_probe_xact
end
go
create procedure sp_probe_xact
	@commid	int,
	@recovery int = NULL
AS
BEGIN
	declare @stat	char(1)
	declare	@suid smallint

	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	begin tran
		IF EXISTS ( SELECT status 
				FROM master.dbo.spt_committab
					WHERE commid = @commid)
		begin
			SELECT @stat = status, @suid = suid
				FROM master.dbo.spt_committab
					WHERE commid = @commid

			/* Only abort non-xa xacts.  The TP Monitor reserves
			** the right to make this decision when xa is in use.
			** The suid is only set by the xa api.  For clasic
			** Sybase 2pc, suid is set to -1.
			*/
			if (@suid = -1) 
			begin
				if ((@stat != 'a') and (@stat != 'c'))
				begin
					update master.dbo.spt_committab
						set status = 'a'
							where commid = @commid
					select status = 'a'
				end
				else
					select status = @stat
			end
			else /* this is an xa tran branch */
			begin

				if (@stat = 'p')
				/* this is an xa tran branch in the prepared 
				** state 
				*/
				begin
					/* end this commit service tran */
					rollback tran

					/* wait for the TP Monitor to update 
					** commit status of this tran branch.
					*/
					while (@stat = 'p')
					begin
						/* check again ever 15 secs */
						waitfor delay "00:00:15"
						SELECT @stat = status
							FROM master.dbo.spt_committab
							WHERE commid = @commid
					end

					/* now return the status */
					select status = @stat
				end
				else
				begin
					if (@stat != 'c')
						select status = 'a'
					else
						select status = 'c'
				end
			end
		end
		else select status = 'u'
	if (@@trancount > 0)
		commit tran
END
go

if exists (select *
		from sysobjects
			where name = "sp_scan_xact")
begin
	drop procedure sp_scan_xact
end
go
create procedure sp_scan_xact 
	@commid	int = NULL
as
BEGIN
	if @@trancount = 0
	begin
		set chained off
	end

	set transaction isolation level 1

	IF	@commid = -1 or @commid is NULL

		SELECT commid,start,lastchange,totnum,outnum,
		       status,applname,xactname
		FROM master.dbo.spt_committab
	ELSE
		SELECT commid,start,lastchange,totnum,outnum,
		       status,applname,xactname
		FROM master.dbo.spt_committab
		WHERE @commid = commid
END
go
exec sp_procxmode 'sp_start_xact', 'anymode'
go
grant execute on sp_start_xact to public
go
dump tran master with truncate_only
go
exec sp_procxmode 'sp_commit_xact', 'anymode'
go
grant execute on sp_commit_xact to public
go
dump tran master with truncate_only
go
exec sp_procxmode 'sp_abort_xact', 'anymode'
go
grant execute on sp_abort_xact to public
go
dump tran master with truncate_only
go
exec sp_procxmode 'sp_remove_xact', 'anymode'
go
grant execute on sp_remove_xact to public
go
dump tran master with truncate_only
go
exec sp_procxmode 'sp_stat_xact', 'anymode'
go
grant execute on sp_stat_xact to public
go
dump tran master with truncate_only
go
exec sp_procxmode 'sp_probe_xact', 'anymode'
go
grant execute on sp_probe_xact to public
go
dump tran master with truncate_only
go
exec sp_procxmode 'sp_scan_xact', 'anymode'
go
grant execute on sp_scan_xact to public
go
dump tran master with truncate_only
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_dbupgrade')
begin
	drop procedure sp_dbupgrade
end
go
print "Installing sp_dbupgrade"
go

/* Sccsid = "%Z% generic/sproc/%M% %I% %G%" */


create procedure sp_dbupgrade
as

if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

/* 
** 	Do the sysindexes column names update which is part of the 38 upgrade.
** 	The sysgams updates have already been taken care of by pg_gamalloc.
*/
print "Upgrading Sysindexes columns in the database"
if not exists (select name from syscolumns where id = 2 and name = 'doampg')
begin
	update syscolumns
	set name = 'doampg'
	where id = 2 and name = 'dpages'
	update syscolumns
	set name = 'ioampg'
	where id = 2 and name = 'reserved'
	update syscolumns
	set name = 'spare1'
	where id = 2 and name = 'used'
	update syscolumns
	set name = 'spare2'
	where id = 2 and name = 'rows'
end

/*	The following updates are part of the 42 upgrade. */

/*
**	Tweak the Syscolumns entries for the Sysindexes table so that 
**	"soid" and "csid" replace half of "usagecnt".
*/
if not exists (select * from syscolumns where id = 2  and  name = 'soid') 
begin
	begin transaction 
	update syscolumns
		set type = 52, length = 2, usertype = 6, offset = 42
		where id = 2  and  colid = 13
	insert into syscolumns
		(id, number, colid, status, type, length, offset,
		 usertype, cdefault, domain, name, printfmt)
	    	values (2, 0, 23, 0, 48, 1, 40, 5, 0, 0, 'soid', '')
	insert into syscolumns
		(id, number, colid, status, type, length, offset,
		 usertype, cdefault, domain, name, printfmt)
	    	values (2, 0, 24, 0, 48, 1, 41, 5, 0, 0, 'csid', '')
	commit transaction
end

print "Adding new datatypes to the database."
if exists (select * from systypes where name = 'text')
 begin 
        delete systypes where name = 'text'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 19, 0, 1, 35, 16, 0, 0, 'text', null) 
if exists (select * from systypes where name = 'image')
 begin 
        delete systypes where name = 'image'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 20, 0, 1, 34, 16, 0, 0, 'image', null) 
if exists (select * from systypes where name = 'timestamp')
 begin 
        delete systypes where name = 'timestamp'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 80, 0, 1, 37, 8, 0, 0, 'timestamp', null) 
if exists (select * from systypes where name = 'smallmoney')
 begin 
        delete systypes where name = 'smallmoney'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 21, 0, 1, 122, 4, 0, 0, 'smallmoney', null) 
if exists (select * from systypes where name = 'smalldatetime')
 begin 
        delete systypes where name = 'smalldatetime'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 22, 0, 1, 58, 4, 0, 0, 'smalldatetime', null) 
if exists (select * from systypes where name = 'real')
 begin 
        delete systypes where name = 'real'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 23, 0, 1, 59, 4, 0, 0, 'real', null) 

/* 4.9 user types for national character */
if exists (select * from systypes where name = 'nchar')
 begin 
        delete systypes where name = 'nchar'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt )
	values (1, 24, 0, 1, 47, 255, 0, 0, 'nchar', null)

if exists (select * from systypes where name = 'nvarchar')
 begin 
        delete systypes where name = 'nvarchar'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 25, 1, 1, 39, 255, 0, 0, 'nvarchar', null) 

if exists (select * from systypes where name = 'NULL')
 begin 
        delete systypes where name = 'NULL'
 end
insert systypes (uid, usertype, variable, allownulls, type, length, 
			tdefault, domain, name, printfmt)
        values (1, 0, 0, 1, 0, 0, 0, 0, 'NULL', null) 

/* 4.9 system table creation */
print "Creating system catalog: sysusermessages and its indexes."
if not exists (select * from sysobjects where name='sysusermessages')
    begin
	execute sp_configure 'allow updates', 1
	reconfigure with override

	dbcc traceon(3701)
	begin
	    create table sysusermessages(error int,uid smallint,
		description varchar(255), langid smallint null)
	    create clustered index csysusermessages
		on sysusermessages (error)
	    create unique nonclustered index ncsysusermessages
		on sysusermessages (error, langid)
	end
	dbcc traceoff(3701)

	execute sp_configure 'allow updates', 0
	reconfigure with override
    end

print "Shutting down SQL Server"
shutdown

return (0)
go
dump transaction sybsystemprocs with truncate_only
go
if exists (select *
	from sysobjects
		where sysstat & 7 = 4
			and name = 'sp_loaddbupgrade')
begin
	drop procedure sp_loaddbupgrade
end
go
print "Installing sp_loaddbupgrade"
go

/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */

create procedure sp_loaddbupgrade 
@databasename varchar(30), 
@devname varchar(30)
as


if @@trancount = 0
begin
	set chained off
end

set transaction isolation level 1

dbcc traceon(3402)

/* The recovery which is part of load database will perform the upgrade */
load database @databasename from @devname

dbcc traceoff(3402)

return (0)
go
dump transaction sybsystemprocs with truncate_only
go
/* Sccsid = "%Z% generic/sproc/src/%M% %I% %G%" */
/*	4.8	1.1	06/14/90	sproc/src/addprobe */
/*
**  This file add the account and user named "probe".  This account is
**  used the 2-phased commit service.
*/
use master
go

if not exists (select *
		from syslogins
			where name = "probe")
begin
	execute sp_addlogin probe, "dontcare"
end
go

if not exists (select *
		from sysusers
			where name = "probe")
begin
	execute sp_adduser probe
end
go

use sybsystemprocs
go
go
dump transaction sybsystemprocs with truncate_only
go
insert master.dbo.spt_values (name, number, type, low)
values ("@(#)ver=11.0.3.3 ESD#6/1/000317", -2, "E", 0)
go
dump transaction sybsystemprocs with truncate_only
go
dump transaction master to diskdump with truncate_only
go
use master
go
sp_configure "allow updates", 0
go
print 'Loading of master database is complete.'
go
