/*
15.5/EBF 17340 SMP/P/x86_64/Enterprise Linux/ase155/2391/64-bit/OPT/Mon Nov  9 14:15:35 2009

Confidential property of Sybase, Inc.
Copyright 1987, 2009
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. One Sybase Drive, Dublin, CA 94568, USA
*/

declare @retval int
exec @retval = sp_version 'installjsdb', NULL, '15.5/EBF 17340 SMP/P/x86_64/Enterprise Linux/ase155/2391/64-bit/OPT/Mon Nov  9 14:15:35 2009', 'start'
if (@retval != 0) select syb_quit()
go

declare @script_versnum int
select @script_versnum = 15500
if (@@version_number < @script_versnum)
begin
	print "'installjsdb' is being run on an older ASE installation. ASE version '%1!', install scripts version '%2!'.",
		@@version_number, @script_versnum
	select syb_quit()
end
go

declare @do_quit int
select @do_quit = 0
if (check_db_upgrade('master') = 0)
begin
	print "'installjsdb' cannot continue, because 'master' database is not upgraded to correct version."
	select @do_quit = 1
end
if (check_db_upgrade('sybmgmtdb') = 0)
begin
	print "'installjsdb' cannot continue, because 'sybmgmtdb' database is not upgraded to correct version."
	select @do_quit = 1
end
if (@do_quit = 1)
	select syb_quit()
go

use master
go
--
-- Install script for the sybmgmtdb - the Sybase Management Database used
-- by the ASE Job Scheduler 
--
/*
** raiserror Messages for js_sybmgmtdb [Total 1]
**
** 19529, "Cannot open database '%1!'. Check the availability of this database and retry the installation."
*/

use master
go
dump tran master with truncate_only
go
print "Starting the setup of sybmgmtdb."
go
--
-- Checking that js roles exist; these are required later in this script
--
if not exists (select name from master..syssrvroles where name = 'js_admin_role')  or
   not exists (select name from master..syssrvroles where name = 'js_user_role')
	select syb_quit()
go
--
-- 1: if sybmgmtdb exists we use it.
-- 2: if sybmgmtdev exists we use it for the sybmgmtdb database.
-- 3: otherwise we create sybmgmtdb on master, providing there is space.
--
if exists (select 1 from sysdatabases where name = "sybmgmtdb")
begin
	print "Using existing sybmgmtdb database."
end
else if exists (select 1 from sysdevices where name = "sybmgmtdev")
begin
	print "Using device sybmgmtdev for the sybmgmtdb database."
end
else
begin
	print "Using device master for the sybmgmtdb database."
end
go
set nocount on
--
-- We check there is sufficient space for at least
--
-- 15M data and 10M of log (2k page),
-- 20M data and 12M of log (4k page),
-- 24M data and 15M of log (8k page),
-- 36M data and 20M of log (16k page).
--
if not exists (select 1 from sysdatabases where name = "sybmgmtdb")
	and exists (select 1 from sysdevices where name = "sybmgmtdev")
begin
	declare @free int, @pgs_mb smallint, @data int, @log int, @device int, @cmd varchar(128)
	declare @db_pagesize int, @pgs_per_page int, @size int, @used int, @min_data int, @min_log int

	select @db_pagesize = v.low from master.dbo.spt_values v where v.number = 1 and v.type = "E"
	if @db_pagesize = 2048
		select @min_data = 15, @min_log = 11
	else if @db_pagesize = 4096
		select @min_data = 20, @min_log = 12
	else if @db_pagesize = 8192
		select @min_data = 24, @min_log = 15
	else
		select @min_data = 36, @min_log = 20

	select @pgs_mb = 1048576 / @@pagesize
	select @pgs_per_page = @db_pagesize / @@pagesize

	select @size = (1 + max(d.high) - max(d.low)) 
          from sysdevices d 
         where d.name = 'sybmgmtdev'

	select @device=d.vdevno from sysdevices d where d.name = 'sybmgmtdev'
	select @used = sum(u.size)
	from sysdevices d, sysusages u
		where u.vdevno = d.vdevno
		and d.vdevno = @device
		and (d.status & 2 = 2)
	if @used is NULL
		select @used = 0
	else	select @used = @used * @pgs_per_page
	select @free = @size - @used

	if @free is NULL or @free = 0
	begin
		print 'Failed to find free space on device sybmgmtdev. Terminating the installation.'
		return
	end

	select @free = @free / @pgs_mb
	if @free < @min_data + @min_log
	begin
		select @size = @min_data + @min_log
		print 'Free space %1! Mb, this is less than the %2! Mb used for the sybmgmtdb database. Terminating the installation.', @free, @size
		return
	end
	--
	-- We use approximately 15% for the log, with a minimum of 10,12,15,20Mb.
	--
	select @log=@free / 7
	if @log < @min_log select @log = @min_log
	select @data=@free - @log
	select @cmd='create database sybmgmtdb on sybmgmtdev = ' 
                + convert(varchar(16), @data)
		+ ' log on sybmgmtdev = ' + convert(varchar(16), @log) 
                + ' with override'
	exec ( @cmd )
end
go
--
if not exists (select 1 from sysdatabases where name = "sybmgmtdb")
	and not exists (select 1 from sysdevices where name = "sybmgmtdev")
begin
	declare @free int, @pgs_mb smallint, @data int, @log int, @device int, @cmd varchar(128)
	declare @db_pagesize int, @pgs_per_page int, @size int, @used int, @min_data int, @min_log int

	select @db_pagesize = v.low from master.dbo.spt_values v where v.number = 1 and v.type = "E"
	if @db_pagesize = 2048
		select @min_data = 15, @min_log = 11
	else if @db_pagesize = 4096
		select @min_data = 20, @min_log = 12
	else if @db_pagesize = 8192
		select @min_data = 24, @min_log = 15
	else
		select @min_data = 36, @min_log = 20

	select @pgs_mb = 1048576 / @@pagesize
	select @pgs_per_page = @db_pagesize / @@pagesize

	select @size = (1 + d.high - d.low) from sysdevices d
		where d.vdevno = 0
		and (d.status & 2 = 2)

	select @used = sum(u.size)
	from sysdevices d, sysusages u
		where u.vdevno = d.vdevno
		and d.vdevno = 0
		and (d.status & 2 = 2)
	if @used is NULL
		select @used = 0
	else	select @used = @used * @pgs_per_page
	select @free = ( @size - @used ) / @pgs_mb

	if @free < @min_data + @min_log
	begin
		select @size = @min_data + @min_log
		print 'Free space %1! Mb, this is less than the %2! Mb used for the sybmgmtdb database. Terminating the installation.', @free, @size
		return
	end
	--
	-- NOTE: the calculation below for sp_js_logthreshold is on 30% free 
        -- space in the log.
	--
	select @log=@free / 15
	if @log < @min_log select @log = @min_log
	select @data=@free - @log
	select @cmd='create database sybmgmtdb on master = ' 
                + convert(varchar(16), @data)
		+ ' log on master = ' + convert(varchar(16), @log) 
                + ' with override'
	exec ( @cmd )
end
go
--
--
--
go
if not exists (select 1 from sysdatabases where name = "sybmgmtdb")
	select syb_quit()
go
sp_dboption sybmgmtdb, "trunc log", true
go
sp_dboption sybmgmtdb, "select into", true
go
use sybmgmtdb
go
if (db_name() != "sybmgmtdb")
begin
	/*
	** 19529, "Cannot open database '%1!'. Check the availability of this database and retry the installation."
	*/
	raiserror 19529, "sybmgmtdb"
	select syb_quit()
end
go
print 'Executing checkpoint in sybmgmtdb'
go
checkpoint
go
set nocount on
go
if exists (select name from sysobjects where name = 'sp_thresholdaction')
	drop proc sp_thresholdaction
go
create proc sp_thresholdaction (@dbname varchar(30), @segment_name varchar(30), @space_left int, @status int)
as
begin
	dump tran @dbname with truncate_only
	return 0
end
go
if exists (select proc_name from systhresholds where proc_name = 'sp_js_logthreshold')
begin
	declare @free_space int
	select @free_space=free_space from systhresholds where proc_name = 'sp_js_logthreshold'
	exec sp_dropthreshold sybmgmtdb, 'logsegment', @free_space
	if exists (select proc_name from systhresholds where proc_name = 'sp_js_logthreshold')
		print 'Unable to drop existing log threshold - sp_js_logthreshold. Terminating the installation.'
end
go
if exists (select proc_name from systhresholds where proc_name = 'sp_js_logthreshold')
	select syb_quit()
go
if exists (select name from sysobjects where name = 'sp_js_logthreshold')
	drop proc sp_js_logthreshold
go
create proc sp_js_logthreshold (@dbname varchar(30), @segment_name varchar(30), @space_left int, @status int)
as
begin
	dump tran @dbname with truncate_only
	return 0
end
go
--
--	calculate 30% of the log, in pages.
--
declare @free_space int
select @free_space=free_space from systhresholds where proc_name = 'sp_thresholdaction'
if @free_space is NULL select @free_space=0
declare @n int, @db_size int
select @db_size=isnull(sum(size), 0) from master..sysusages where dbid = db_id('sybmgmtdb') and segmap = 4
select @n=(@db_size * 30 ) / 100
print 'Database log is %1! pages, 30%% log free is at %2! pages, the last chance threshold is at %3! pages.',
	@db_size, @n, @free_space
if @n <= @free_space + (2 * @@thresh_hysteresis)
begin
	select @n= @free_space + (2 * @@thresh_hysteresis) + 1
	print 'A 30%% free threshold is too close to the last chance threshold and must be moved to %1! pages.', @n
end
print 'installing sp_js_logthreshold at %1! pages.', @n
exec sp_addthreshold sybmgmtdb, logsegment, @n, sp_js_logthreshold
go
if not exists (select proc_name from systhresholds where proc_name = 'sp_js_logthreshold')
	print 'Unable to create log threshold - sp_js_logthreshold. Terminating the installation.'
go
if not exists (select proc_name from systhresholds where proc_name = 'sp_js_logthreshold')
	select syb_quit()
go
--
--	If referenced tables are dropped then the order is:-
--
--	drop js_xml before js_templates
--	drop js_commands before js_jobs
--	drop index js_jobs.idx_job_name
--	drop index js_schedules.idx_sched_name
--	drop index js_scheduledjobs.idx_sjobname
--	drop index js_templates.idx_jtmpl_name
--	drop js_jobs and js_schedules before js_scheduledjobs
--
go
if not exists (select name from sysobjects where name = "js_jobs")
begin
	exec ("create table js_jobs
	(
	job_id			int				not null,
		primary key (job_id),
	job_update		int		default 0	not null,
	job_type		int				not null,
	job_properties		int		default 0	not null,
	job_owner		varchar(30)			not null,
	job_created		datetime			not null,
	job_default_timeout	int		default 0	not null,
	job_tmpl_id		int				null,
	job_name		univarchar(64)			not null,
	job_description		univarchar(128)			null,
	job_uproperties		varchar(128)			null,

	constraint check_job_type check (job_type in (0, 1, 2, 3)),
	constraint check_job_timeout check (job_default_timeout >= 0)

	) lock datarows")

	exec ("create nonclustered index idx_job_name on js_jobs (job_name)")
print "Created js_jobs."
end
go
if not exists (select name from sysobjects where name = "js_commands")
begin
	exec ("create table js_commands
	(
	jcmd_job_id		int				not null references js_jobs(job_id),
	jcmd_type		int				not null,
	jcmd_seqno		int				not null,
	jcmd_text		univarchar(901)			null,
	constraint check_jcmd_type check (jcmd_type = 0),

	primary key (jcmd_job_id, jcmd_seqno)
	) lock datarows")
print "Created js_commands."
end
go
if not exists (select name from sysobjects where name = "js_schedules")
begin
	exec ("create table js_schedules
	(
	sched_id		int				not null,
		primary key (sched_id),
	sched_update		int		default 0	not null,
	sched_type		int				not null,
	sched_properties	int		default 0	not null,
	sched_owner		varchar(30)			not null,
	sched_created		datetime			not null,

	sched_interval		int		default 0	not null,
	sched_interval_units	char(1)		default ' '	not null,
	sched_startdate		datetime			null,
	sched_starttime		datetime			null,
	sched_enddate		datetime			null,
	sched_endtime		datetime			null,

	sched_days		smallint	default 0	not null,
	sched_dates		int		default 0	not null,

	sched_name		univarchar(64)			not null,
	sched_description	univarchar(128)			null,
	sched_uproperties	varchar(128)			null,
	sched_uinterval		varchar(32)			null,
	sched_udays		varchar(128)			null,
	sched_udates		varchar(128)			null,
	sched_expired		int		default 0	not null,

	constraint check_sched_interval check (sched_interval >= 0),
	constraint check_sched_interval_units check (sched_interval_units like '[ smhd]'),
	constraint check_sched_days check (sched_days between 0 and 127)

	) lock datarows")

	exec ("create nonclustered index idx_sched_name on js_schedules (sched_name)")
print "Created js_schedules."
end
go
if not exists (select name from sysobjects where name = "js_scheduledjobs")
begin
	exec ("create table js_scheduledjobs
	(
	sjob_id			int				not null,
		primary key (sjob_id),
	sjob_job_id		int	references js_jobs(job_id),
	sjob_sched_id		int	references js_schedules(sched_id),

	sjob_update		int		default 0	not null,
	sjob_enable		smallint	default 1	not null,
	sjob_properties		int		default 0	not null,
	sjob_created		datetime			null,
	sjob_timeout_value	int		default 0	not null,
	sjob_owner		varchar(30)			null,
	sjob_server		varchar(30)			null,
	sjob_locale		varchar(30)			null,
	sjob_name		univarchar(64)			null,
	sjob_uproperties	varchar(128)			null,
	
	constraint check_sjob_enable check (sjob_enable in (0,1))

	) lock datarows")

	exec ("create nonclustered index idx_sjob_name on js_scheduledjobs (sjob_name)")
print "Created js_scheduledjobs."
end
go
if not exists (select name from sysobjects where name = "js_seqsql")
begin
	exec ("create table js_seqsql
	(
	ssql_sid		int				not null,
	ssql_type		int		default 0	not null,
	ssql_seqno		int		default 0	not null,
	ssql_name		varchar(32)			not null,
	ssql_sql		varchar(1800)			null,

	primary key (ssql_sid, ssql_seqno)
	) lock datarows")
print "Created js_seqsql."
end
go
if not exists (select name from sysobjects where name = "js_callouts")
begin
	exec ("create table js_callouts
	(
	jsc_calloutid		int		default 0	not null,
	jsc_sjobid		int				not null,
	jsc_condid		int				not null,
	jsc_bsqlid		int				null,
	jsc_esqlid		int				null,

	jsc_jtype		int		default 0	not null,
	jsc_state		char(2)		default 'W'	not null,
	jsc_start		datetime			null,
	jsc_timeout		int		default 0	not null,
	jsc_modified		int				null,
	jsc_user_req		varchar(30)			null,
	constraint check_jsc_state check
		(jsc_state in ('W', 'Q', 'B', 'R1', 'R2', 'C1', 'C2', 'T1', 'T2', 'X1', 'X2', 'M', 'E')),

	) lock datarows")

	exec ("create nonclustered index idx_jsc_calloutid on js_callouts (jsc_calloutid)")
	exec ("create nonclustered index idx_jsc_sjobid on js_callouts (jsc_sjobid)")
print "Created js_callouts."
end
go
if not exists (select name from sysobjects where name = "js_history")
begin
	exec ("create table js_history
	(
	jsh_exid		int				not null,
	jsh_sjobid		int				not null,
	jsh_condid		int		default 0	not null,
	jsh_jobname		univarchar(64)			not null,
	jsh_schedname		univarchar(64)			not null,

	jsh_jtype		int		default 0	not null,
	jsh_state		char(2)		default 'M'	not null,
	jsh_exit_code		smallint	default 0	not null,
	jsh_user_code		int		default 0	not null,
	jsh_atat_error		int		default 0	not null,
	jsh_os_code		int		default 0	not null,

	jsh_jobstart		datetime	default getdate() null,
	jsh_jobend		datetime			null,
	jsh_user_run		varchar(30)			not null,
	jsh_user_req		varchar(30)			not null,
	jsh_size		int		default 0	not null,
	jsh_smsg		univarchar(64)			null,
	jsh_lmsg		univarchar(255)			null,
	jsh_update		int		default 0	not null,
	jsh_spid		int		default 0	not null,
	constraint check_jsh_state check
		(jsh_state in ('W', 'Q', 'B', 'R1', 'R2', 'C1', 'C2', 'T1', 'T2', 'X1', 'X2', 'M')),
	constraint check_jsh_exit_code check (jsh_exit_code in (0, 1, 2, 3, 4))

	) lock datarows")

	exec ("create clustered index jsh_exid_index on js_history (jsh_exid desc) with allow_dup_row")
print "Created js_history."
end
go
if not exists (select name from sysobjects where name = "js_output")
begin
	exec ("create table js_output
	(
	jsout_exid		int				not null,
	jsout_type		int		default 0	not null,
	jsout_size		int		default 0	not null,
	jsout_seqno		int				not null,
	jsout_text		univarchar(901)			null,

	primary key (jsout_exid, jsout_seqno)
	) lock datarows")
print "Created js_output."
end
go
if not exists (select name from sysobjects where name = "js_keys")
begin
	exec ("create table js_keys
	(
	jskey_name		varchar(64)			not null,
	jskey_id		int				not null,
	jskey_lock		int				not null,
--	jskey_table		varchar(32)			not null,
		primary key clustered (jskey_name, jskey_id)
	) lock datarows")
print "Created js_keys."
end
go
if exists (select name from sysobjects where name = "js_keys")
begin
	if not exists (select jskey_name from js_keys where jskey_name = 'job_id')
		insert into js_keys values ('job_id', 1, 0)
	if not exists (select jskey_name from js_keys where jskey_name = 'sched_id')
		insert into js_keys values ('sched_id', 1, 0)
	if not exists (select jskey_name from js_keys where jskey_name = 'sjob_id')
		insert into js_keys values ('sjob_id', 1, 0)
	if not exists (select jskey_name from js_keys where jskey_name = 'jsh_exid')
		insert into js_keys values ('jsh_exid', 1, 0)
	if not exists (select jskey_name from js_keys where jskey_name = 'jtmpl_id')
		insert into js_keys values ('jtmpl_id', 1, 0)
end
go
if not exists (select name from sysobjects where name = "js_templates")
begin
	exec ("create table js_templates
	(
	jtmpl_id		int				not null,
	jtmpl_type		int				not null,
	jtmpl_name		univarchar(64)			not null,
	jtmpl_description	univarchar(128)			null,
	jtmpl_owner		varchar(30)			not null,
	jtmpl_created		datetime			not null,
	jtmpl_version		univarchar(16)			null,
	jtmpl_group_path	univarchar(256)			null,
	jtmpl_update		int		default 0	not null,
	jtmpl_language		univarchar(32)			null,
	constraint check_jtmpl_type check (jtmpl_type in (0)),

	primary key (jtmpl_id)
	) lock datarows")

	exec ("create nonclustered index idx_jtmpl_name on js_templates (jtmpl_name)")
print "Created js_templates."
end
go
if not exists (select name from sysobjects where name = "js_xml")
begin
	exec ("create table js_xml
	(
	jxml_jtmpl_id		int				not null references js_templates(jtmpl_id),
	jxml_type		int				not null,
	jxml_seqno		int				not null,
	jxml_text		univarchar(901)			null,
	constraint check_jxml_type check (jxml_type = 0),

	primary key (jxml_jtmpl_id, jxml_seqno)
	) lock datarows")
print "Created js_xml."
end
go
if not exists (select name from sysobjects where name = "js_daynames")
begin
	exec ("create table js_daynames
	(
	jsday_lang		univarchar(32)			not null,
	jsday_sun		univarchar(32)			not null,
	jsday_mon		univarchar(32)			not null,
	jsday_tue		univarchar(32)			not null,
	jsday_wed		univarchar(32)			not null,
	jsday_thu		univarchar(32)			not null,
	jsday_fri		univarchar(32)			not null,
	jsday_sat		univarchar(32)			not null,
	primary key (jsday_lang)
	) lock datarows")
print "Created js_daynames."
end
go
checkpoint
go
if not exists (select name from sysobjects where name = "js_jobs")	or
   not exists (select name from sysobjects where name = "js_commands")	or
   not exists (select name from sysobjects where name = "js_schedules")	or
   not exists (select name from sysobjects where name = "js_scheduledjobs")	or
   not exists (select name from sysobjects where name = "js_seqsql")	or
   not exists (select name from sysobjects where name = "js_callouts")	or
   not exists (select name from sysobjects where name = "js_history")	or
   not exists (select name from sysobjects where name = "js_output")	or
   not exists (select name from sysobjects where name = "js_keys")	or
   not exists (select name from sysobjects where name = "js_templates")	or
   not exists (select name from sysobjects where name = "js_xml")	or
   not exists (select name from sysobjects where name = "js_daynames")
	print 'Unable to create Job Scheduler tables. Terminiating the installation.'
go
if not exists (select name from sysobjects where name = "js_jobs")	or
   not exists (select name from sysobjects where name = "js_commands")	or
   not exists (select name from sysobjects where name = "js_schedules")	or
   not exists (select name from sysobjects where name = "js_scheduledjobs")	or
   not exists (select name from sysobjects where name = "js_seqsql")	or
   not exists (select name from sysobjects where name = "js_callouts")	or
   not exists (select name from sysobjects where name = "js_history")	or
   not exists (select name from sysobjects where name = "js_output")	or
   not exists (select name from sysobjects where name = "js_keys")	or
   not exists (select name from sysobjects where name = "js_templates")	or
   not exists (select name from sysobjects where name = "js_xml")	or
   not exists (select name from sysobjects where name = "js_daynames")
	select syb_quit()
go
--
-- Upgrade Job Scheduler to support unichar
--
use tempdb
go
if exists (select name from tempdb..sysobjects where name = 'sp_sjobcoltype')
	drop proc sp_sjobcoltype
go
create proc sp_sjobcoltype (
	@tabname varchar(64),
	@colname varchar(64),
	@type    varchar(64)
)
as
begin
	if not exists (select 1 from master..sysdatabases where name = 'sybmgmtdb')
		return 0
	if exists (select type from sybmgmtdb..syscolumns
		where name=@colname
			and id=(select id from sybmgmtdb..sysobjects where name = @tabname and type = 'U')
			and type=(select type from sybmgmtdb..systypes where name = @type)
		)
		return 1
	else
		return 0
end
go
use sybmgmtdb
go
if (db_name() != "sybmgmtdb")
begin
	/*
	** 19529, "Cannot open database '%1!'. Check the availability of this database and retry the installation."
	*/
	raiserror 19529, "sybmgmtdb"
	select syb_quit()
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_commands', 'jcmd_text', 'varchar'
if @ret = 1
begin
	print "Checking Job Scheduler tables for upgrade"
	print 'Checking data in js_commands, js_output and js_xml'
end
go
--
-- Check for any data that will not fit into the smaller jcmd_text and jsout_text columns.
-- If there is, we have to split it and re-write the sequence numbers.
--
declare @ret int, @id int, @last_id int, @max_seqno int, @new_seqno int, @ncols int, @len int
declare @chunk1 varchar(1801), @chunk2 varchar(901), @err int
exec @ret=tempdb..sp_sjobcoltype 'js_commands', 'jcmd_text', 'varchar'
if @ret = 1
begin
	set rowcount 1
	select @last_id=0, @err=0
	select @id=min(jcmd_job_id) from sybmgmtdb..js_commands
		where jcmd_job_id > @last_id and char_length(jcmd_text) > 901
	begin tran js_commands
	save  tran jcmd_text
	while @id is not NULL and @err = 0
	begin
		select @max_seqno=max(jcmd_seqno) from sybmgmtdb..js_commands where jcmd_job_id=@id
		select @ncols=count(jcmd_seqno) from sybmgmtdb..js_commands
			where jcmd_job_id=@id and char_length(jcmd_text) > 901
		select @new_seqno=@max_seqno + @ncols
		--
		while @max_seqno >= 0 and @err = 0
		begin
			select @len=char_length(jcmd_text) from sybmgmtdb..js_commands
				where jcmd_job_id=@id and jcmd_seqno=@max_seqno
			if @@rowcount <= 0
			begin
				select @max_seqno=@max_seqno - 1
			end
			else if @len <= 901
			begin
				update sybmgmtdb..js_commands set jcmd_seqno=@new_seqno
					where jcmd_job_id=@id and jcmd_seqno=@max_seqno
				select @err=@@error
				select @new_seqno=@new_seqno - 1
				select @max_seqno=@max_seqno - 1
			end
			else
			begin
				select @chunk1=jcmd_text from sybmgmtdb..js_commands
					where jcmd_job_id=@id and jcmd_seqno=@max_seqno
				select @chunk2=substring(@chunk1, 901, 901)
				select @chunk1=substring(@chunk1, 1, 900) + char(10)
				insert sybmgmtdb..js_commands (jcmd_job_id, jcmd_type, jcmd_seqno, jcmd_text)
					values (@id, 0, @new_seqno, @chunk2)
				select @err=@@error
				if @err = 0
				begin
					select @new_seqno=@new_seqno - 1
					update sybmgmtdb..js_commands set jcmd_seqno=@new_seqno, jcmd_text=@chunk1
						where jcmd_job_id=@id and jcmd_seqno=@max_seqno
					select @err=@@error
				end
				select @new_seqno=@new_seqno - 1
				select @max_seqno=@max_seqno - 1
			end
		end
		select @last_id=@id
		select @id=min(jcmd_job_id) from sybmgmtdb..js_commands
			where jcmd_job_id > @last_id and char_length(jcmd_text) > 901
	end
	if @err != 0
		rollback tran jcmd_text
	commit tran jcmd_text
	set rowcount 0
end
go
if exists (select jcmd_job_id from sybmgmtdb..js_commands where char_length(jcmd_text) > 901)
	print 'A failure occured while re-writing the js_commands table, rolled back and stopping the install'
go
if exists (select jcmd_job_id from sybmgmtdb..js_commands where char_length(jcmd_text) > 901)
	select syb_quit()
go
--
--
declare @ret int, @id int, @last_id int, @max_seqno int, @new_seqno int, @ncols int, @len int
declare @chunk1 varchar(1801), @chunk2 varchar(901), @err int
exec @ret=tempdb..sp_sjobcoltype 'js_xml', 'jxml_text', 'varchar'
if @ret = 1
begin
	set rowcount 1
	select @last_id=0, @err=0
	select @id=min(jxml_jtmpl_id) from sybmgmtdb..js_xml
		where jxml_jtmpl_id > @last_id and char_length(jxml_text) > 901
	begin tran js_xml
	save  tran jxml_text
	while @id is not NULL and @err = 0
	begin
		select @max_seqno=max(jxml_seqno) from sybmgmtdb..js_xml where jxml_jtmpl_id=@id
		select @ncols=count(jxml_seqno) from sybmgmtdb..js_xml
			where jxml_jtmpl_id=@id and char_length(jxml_text) > 901
		select @new_seqno=@max_seqno + @ncols
		--
		while @max_seqno >= 0 and @err = 0
		begin
			select @len=char_length(jxml_text) from sybmgmtdb..js_xml
				where jxml_jtmpl_id=@id and jxml_seqno=@max_seqno
			if @@rowcount <= 0
			begin
				select @max_seqno=@max_seqno - 1
			end
			else if @len <= 901
			begin
				update sybmgmtdb..js_xml set jxml_seqno=@new_seqno
					where jxml_jtmpl_id=@id and jxml_seqno=@max_seqno
				select @err=@@error
				select @new_seqno=@new_seqno - 1
				select @max_seqno=@max_seqno - 1
			end
			else
			begin
				select @chunk1=jxml_text from sybmgmtdb..js_xml
					where jxml_jtmpl_id=@id and jxml_seqno=@max_seqno
				select @chunk2=substring(@chunk1, 901, 901)
				select @chunk1=substring(@chunk1, 1, 900) + char(10)
				insert sybmgmtdb..js_xml (jxml_jtmpl_id, jxml_type, jxml_seqno, jxml_text)
					values (@id, 0, @new_seqno, @chunk2)
				select @err=@@error
				if @err = 0
				begin
					select @new_seqno=@new_seqno - 1
					update sybmgmtdb..js_xml set jxml_seqno=@new_seqno, jxml_text=@chunk1
						where jxml_jtmpl_id=@id and jxml_seqno=@max_seqno
					select @err=@@error
				end
				select @new_seqno=@new_seqno - 1
				select @max_seqno=@max_seqno - 1
			end
		end
		select @last_id=@id
		select @id=min(jxml_jtmpl_id) from sybmgmtdb..js_xml
			where jxml_jtmpl_id > @last_id and char_length(jxml_text) > 901
	end
	if @err != 0
		rollback tran jxml_text
	commit tran jxml_text
	set rowcount 0
end
go
if exists (select jxml_jtmpl_id from sybmgmtdb..js_xml where char_length(jxml_text) > 901)
	print 'A failure occured while re-writing the js_xml table, rolled back and stopping the install'
go
if exists (select jxml_jtmpl_id from sybmgmtdb..js_xml where char_length(jxml_text) > 901)
	select syb_quit()
go
--
--
declare @ret int, @id int, @last_id int, @max_seqno int, @new_seqno int, @ncols int, @len int
declare @chunk1 varchar(1801), @chunk2 varchar(901), @size int, @err int
exec @ret=tempdb..sp_sjobcoltype 'js_output', 'jsout_text', 'varchar'
if @ret = 1
begin
	set rowcount 1
	select @last_id=0, @err=0
	select @id=min(jsout_exid) from sybmgmtdb..js_output
		where jsout_exid > @last_id and char_length(jsout_text) > 901
	begin tran js_output
	save  tran jsout_text
	while @id is not NULL and @err = 0
	begin
		select @max_seqno=max(jsout_seqno) from sybmgmtdb..js_output where jsout_exid=@id
		select @ncols=count(jsout_seqno) from sybmgmtdb..js_output
			where jsout_exid=@id and char_length(jsout_text) > 901
		select @new_seqno=@max_seqno + @ncols
		--
		while @max_seqno >= 0 and @err = 0
		begin
			select @len=char_length(jsout_text) from sybmgmtdb..js_output
				where jsout_exid=@id and jsout_seqno=@max_seqno
			if @@rowcount <= 0
			begin
				select @max_seqno=@max_seqno - 1
			end
			else if @len <= 901
			begin
				select @size=@len - 1
				update sybmgmtdb..js_output set jsout_seqno=@new_seqno, jsout_size=@size
					where jsout_exid=@id and jsout_seqno=@max_seqno
				select @err=@@error
				select @new_seqno=@new_seqno - 1
				select @max_seqno=@max_seqno - 1
			end
			else
			begin
				select @size=@len - 1
				select @chunk1=jsout_text from sybmgmtdb..js_output
					where jsout_exid=@id and jsout_seqno=@max_seqno
				select @chunk2=substring(@chunk1, 901, 901)
				select @chunk1=substring(@chunk1, 1, 900) + char(10)
				insert sybmgmtdb..js_output (jsout_exid, jsout_type, jsout_size, jsout_seqno, jsout_text)
					values (@id, 0, 900, @new_seqno, @chunk2)
				select @err=@@error
				if @err = 0
				begin
					select @new_seqno=@new_seqno - 1
					select @size=@size - 900
					update sybmgmtdb..js_output set jsout_seqno=@new_seqno, jsout_text=@chunk1,
							jsout_size=@size
						where jsout_exid=@id and jsout_seqno=@max_seqno
					select @err=@@error
				end
				select @new_seqno=@new_seqno - 1
				select @max_seqno=@max_seqno - 1
			end
		end
		select @last_id=@id
		select @id=min(jsout_exid) from sybmgmtdb..js_output
			where jsout_exid > @last_id and char_length(jsout_text) > 901
	end
	if @err != 0
		rollback tran jsout_text
	commit tran
	set rowcount 0
end
go
if exists (select jsout_exid from sybmgmtdb..js_output where char_length(jsout_text) > 901)
	print 'A failure occured while re-writing the js_output table, rolled back and stopping the install'
go
if exists (select jsout_exid from sybmgmtdb..js_output where char_length(jsout_text) > 901)
	select syb_quit()
go
--
-- Now check for columns that need to be converted to unichar
--
-- This is a vulnerable part of the install as we cannot put alter tables into a
-- transaction. So any failures here are serious and may require a db restore.
--
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_jobs', 'job_name', 'varchar'
if @ret = 1
begin
	print 'Checking columns'
	exec ("alter table sybmgmtdb..js_jobs modify job_name univarchar(64) not null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_jobs', 'job_description', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_jobs modify job_description univarchar(128) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_commands', 'jcmd_text', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_commands modify jcmd_text univarchar(901) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_schedules', 'sched_name', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_schedules modify sched_name univarchar(64) not null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_schedules', 'sched_description', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_schedules modify sched_description univarchar(128) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'scheduledjobs', 'sjob_name', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_scheduledjobs modify sjob_name univarchar(64) not null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_history', 'jsh_jobname', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_history modify jsh_jobname univarchar(64) not null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_history', 'jsh_schedname', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_history modify jsh_schedname univarchar(64) not null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_history', 'jsh_smsg', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_history modify jsh_smsg univarchar(64) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_history', 'jsh_lmsg', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_history modify jsh_lmsg univarchar(255) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_output', 'jsout_text', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_output modify jsout_text univarchar(901) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_templates', 'jtmpl_name', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_templates modify jtmpl_name univarchar(64) not null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_templates', 'jtmpl_description', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_templates modify jtmpl_description univarchar(128) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_templates', 'jtmpl_version', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_templates modify jtmpl_version univarchar(16) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_templates', 'jtmpl_group_path', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_templates modify jtmpl_group_path univarchar(256) null")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_templates', 'jtmpl_language', 'univarchar'
if @ret = 0
begin
	exec ("alter table sybmgmtdb..js_templates add jtmpl_language univarchar(32) null")
	exec ("update sybmgmtdb..js_templates set jtmpl_language='en' where jtmpl_language is NULL")
end
go
declare @ret int
exec @ret=tempdb..sp_sjobcoltype 'js_dynames', 'jsday_lang', 'varchar'
if @ret = 1
begin
	exec ("alter table sybmgmtdb..js_daynames modify jsday_lang univarchar(32) not null")
	exec ("alter table sybmgmtdb..js_daynames modify jsday_sun univarchar(32) not null")
	exec ("alter table sybmgmtdb..js_daynames modify jsday_mon univarchar(32) not null")
	exec ("alter table sybmgmtdb..js_daynames modify jsday_tue univarchar(32) not null")
	exec ("alter table sybmgmtdb..js_daynames modify jsday_wed univarchar(32) not null")
	exec ("alter table sybmgmtdb..js_daynames modify jsday_thu univarchar(32) not null")
	exec ("alter table sybmgmtdb..js_daynames modify jsday_fri univarchar(32) not null")
	exec ("alter table sybmgmtdb..js_daynames modify jsday_sat univarchar(32) not null")
	print "Completed checking Job Scheduler tables for upgrade"
end
print "Setup of sybmgmtdb is done."
go
/*****************************************************************
** Install jstask user and js_admin_role			**
** This needs further attention but we need it for quasr tests	**
*****************************************************************/
/*
** raiserror Messages for js_sequencer [Total 3]
**
** 19529, "Cannot open database '%1!'. Check the availability of this database and retry the installation."
** 19929, "master.dbo.sp_extrapwdchecks exists. Manually create jstask login account before retrying Job Scheduler installation."
** 19930, "Correct password complexity validation errors or manually create jstask login account before retrying Job Scheduler installation."
*/

use master
go
if not exists (select name from master..syslogins where name = 'jstask')
begin
	if object_id("master.dbo.sp_extrapwdchecks") <> NULL
	begin
		raiserror 19929
		select syb_quit()
	end
	declare @password varchar(30)
	select @password = password_random()
	if (char_length(@password) = NULL)
	begin
		raiserror 19930
		select syb_quit()
	end
	else
	begin
		exec sp_addlogin jstask, @password
	end
end
exec sp_locklogin jstask, 'lock'
exec sp_role 'grant', js_admin_role, jstask
exec sp_role 'grant', js_user_role, jstask
exec sp_modifylogin jstask, 'add default role', js_user_role
exec sp_modifylogin jstask, 'add default role', js_admin_role
go

use sybmgmtdb
go
if (db_name() != "sybmgmtdb")
begin
	/*
	** 19529, "Cannot open database '%1!'. Check the availability of this database and retry the installation."
	*/
	raiserror 19529, "sybmgmtdb"
	select syb_quit()
end
go
if not exists (select name from sybmgmtdb..sysusers where name = 'jstask')
	exec sp_adduser jstask
go

/*****************************************************************
** FOR INTERNAL USE ONLY					**
**								**
** This install script adds the required Job Scheduler ASE Task	**
** sequencer code under the "js_seqsql" table.  Up on boot,	**
** stage 1, for the Job Scheduler ASE task this table is read 	**
** into dedicated JS memory.					**
**								**
** The JS Sequencer code is required for the normal JS chore	**
** process cycles and allows for flexible updates without	**
** rebuilding ASE.						**
**								**
** Wim ten Have <wtenhave@sybase.com>				**
** Mon Nov 25 13:34:56 MET 2002					**
*****************************************************************/

set nocount on
go
print "Installing Job Scheduler Task js_seqsql sequencer code"
go
use sybmgmtdb
go
if (db_name() != "sybmgmtdb")
begin
	/*
	** 19529, "Cannot open database '%1!'. Check the availability of this database and retry the installation."
	*/
	raiserror 19529, "sybmgmtdb"
	select syb_quit()
end
go
delete from js_seqsql
go


/*****************************************************************
** This entry makes our FIRMWARE definition			**
** when the JS Task is booted and the sequencer tokens are	**
** loaded the major number and token count should always match	**
** the minor number is allowed to increment under the condition	**
** that none of the dynamic tokens did change in functionality	**
**                                                              **
** Note: sjam automatically generates the jsfirmware.h file     **
** from this stanza using the genjsfirmware perl script in the  **
** $DBMS/generic/source/demo directory. This script relies on   **
** the key:value format where the major, minor and sqcnt keys   **
** are all on a single line. If this format is changed then the **
** search pattern in genjsfirmware MUST be changed as well for  **
** jsfirmware.h to be generated correctly.                      **
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=0)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (0, 0,
	"BOOTSTRAP FIRMWARE$", 
	"major:0 minor:27 sqcnt:27 jstask:jstask$")
go
print ": js_seqsql installed token  0 - BOOTSTRAP FIRMWARE"
go


/*****************************************************************
** check the existense of the "js_callouts" table.		**
** this entry is effectively fake as it is also hardcoded to	**
** assure that the boot-strap succeeds. (WTH)			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=1)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (1, 0,
"PROBE JS_CALLOUTS$",
"DECLARE @id int
 SELECT  @id = SIGN(ISNULL(OBJECT_ID('js_callouts'),0))
 PRINT	"":i: %%1!"", @id
$")
go
print ": js_seqsql installed token  1 - PROBE JS_CALLOUTS"
go


/*****************************************************************
** check the existense of the "js_history" table.		**
** this entry is effectively fake as it is also hardcoded to	**
** assure that the boot-strap succeeds. (WTH)			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=2)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (2, 0,
"PROBE JS_HISTORY$",
"DECLARE @id int
 SELECT  @id = SIGN(ISNULL(OBJECT_ID('js_history'),0)) 
 PRINT  "":i: %%1!"", @id
$")
go
print ": js_seqsql installed token  2 - PROBE JS_HISTORY"
go


/*****************************************************************
** copy all (M)issed callouts under "js_history"		**
** needs further attention as we need to recalculate the 	**
** next callout time. (WTH)					**
** 	0 = failed, ie there are still rows in js_calouts	**
**	1 = succes, js_callouts table is empty			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=3)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (3, 0,
"CLEAN JS_CALLOUTS$",
"DECLARE @ret int, @max_exid int, @jsc_exid int
 SELECT @max_exid=max(jsh_exid) FROM js_history
 IF @max_exid is NULL SELECT @max_exid=0
 SELECT @jsc_exid=@max_exid, @ret=1
 UPDATE js_callouts SET jsc_calloutid=@jsc_exid
 UPDATE js_callouts SET jsc_user_req=sjob_owner FROM js_callouts, js_scheduledjobs
	WHERE js_callouts.jsc_sjobid=js_scheduledjobs.sjob_id AND js_callouts.jsc_user_req is NULL

 SET rowcount 1
 WHILE @ret=1
 BEGIN
	SELECT @max_exid=@max_exid + 1
	UPDATE js_callouts SET jsc_calloutid=@max_exid WHERE jsc_calloutid=@jsc_exid
	SELECT @ret=@@rowcount
 END 
 SET rowcount 0

 INSERT js_history (
	jsh_exid,
	jsh_sjobid,
	jsh_condid,
	jsh_jobname,
	jsh_schedname,
	jsh_jtype,
	jsh_jobstart,
	jsh_user_run,
	jsh_user_req)
 SELECT jc.jsc_calloutid,
	jc.jsc_sjobid,
	jc.jsc_condid,
	jo.job_name,
	js.sched_name,
	jc.jsc_jtype,
	jc.jsc_start,
	jo.job_owner,
	jc.jsc_user_req
 FROM   js_callouts jc,
	js_scheduledjobs jj,
	js_schedules js,
	js_jobs jo
 WHERE  jc.jsc_start < getdate()  AND jj.sjob_id=jc.jsc_sjobid  AND jj.sjob_sched_id=js.sched_id AND jj.sjob_job_id=jo.job_id AND (jo.job_properties & 2)=2

 INSERT js_history (
	jsh_exid,
	jsh_sjobid,
	jsh_condid,
	jsh_jobname,
	jsh_schedname,
	jsh_jtype,
	jsh_jobstart,
	jsh_user_run,
	jsh_user_req)
 SELECT jc.jsc_calloutid,
	jc.jsc_sjobid,
	jc.jsc_condid,
	jo.job_name,
	js.sched_name,
	jc.jsc_jtype,
	jc.jsc_start,
	jc.jsc_user_req,
	jc.jsc_user_req
 FROM   js_callouts jc,
	js_scheduledjobs jj,
	js_schedules js,
	js_jobs jo
 WHERE  jc.jsc_start < getdate()  AND jj.sjob_id=jc.jsc_sjobid  AND jj.sjob_sched_id=js.sched_id AND jj.sjob_job_id=jo.job_id AND (jo.job_properties & 2)=0

 TRUNCATE TABLE js_callouts
 IF EXISTS (SELECT 1 from js_callouts) 
	SELECT @ret = 0 ELSE SELECT @ret = 1
 PRINT  "":i: %%1!"", @ret
$")
go
print ": js_seqsql installed token  3 - CLEAN JS_CALLOUTS"
go


/*****************************************************************
** Inital population of js_callouts				**
** the returned rowcount reports the number of jobs to schedule	**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=4)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (4, 0,
"POPULATE JS_CALLOUTS$",
"DECLARE @rows int, @max_exid int, @ret int

 INSERT INTO js_callouts (
	jsc_calloutid,
	jsc_sjobid,
	jsc_jtype,
	jsc_timeout,
	jsc_modified,
	jsc_condid,
	jsc_state )
 SELECT 0,
	sj.sjob_id,
	jd.job_type,
	sj.sjob_timeout_value,
	1,
	0,
	'W'
 FROM 	js_scheduledjobs sj,
	js_jobs jd,
	js_schedules sd
 WHERE  sj.sjob_job_id=jd.job_id AND sj.sjob_sched_id=sd.sched_id
	AND sj.sjob_timeout_value != 0 AND sj.sjob_enable != 0
	AND (sd.sched_expired & 1) != 1
 SELECT @ret=@@rowcount

 INSERT INTO js_callouts (
	jsc_calloutid,
	jsc_sjobid,
	jsc_jtype,
	jsc_timeout,
	jsc_modified,
	jsc_condid,
	jsc_state )
 SELECT 0,
	sj.sjob_id,
	jd.job_type,
	jd.job_default_timeout,
	1,
	0,
	'W'
 FROM 	js_scheduledjobs sj,
	js_jobs jd,
	js_schedules sd
 WHERE  sj.sjob_job_id=jd.job_id AND sj.sjob_sched_id=sd.sched_id
	AND sj.sjob_timeout_value = 0 AND sj.sjob_enable != 0
	AND (sd.sched_expired & 1) != 1
 SELECT @ret=@ret + @@rowcount

 SELECT @max_exid=max(jsh_exid) FROM js_history
 IF @max_exid is NULL SELECT @max_exid=0
 SELECT @rows=1
 
 SET rowcount 1
 WHILE @rows=1
 BEGIN
	SELECT @max_exid=@max_exid + 1
	UPDATE js_callouts SET jsc_calloutid=@max_exid WHERE jsc_calloutid=0
	SELECT @rows=@@rowcount
 END 
 SET rowcount 0

 PRINT  "":i: %%1!"", @ret
$")
go
print ": js_seqsql installed token  4 - POPULATE JS_CALLOUTS"
go


/*****************************************************************
** collect the table size for our callout list			**
** this token is not necessarily required it can be processed	**
** under the GET VALUE token.					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=5)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (5, 0,
"GET CALLOUT SIZE$",
"DECLARE @calloutsize int
	SELECT @calloutsize = ISNULL (count(*), 0)
	FROM   js_callouts

	PRINT  "":i: %%1!"", @calloutsize
$")
go
print ": js_seqsql installed token  5 - GET CALLOUT SIZE"
go


/*****************************************************************
**	Load a js_callouts slot into memory			**
**	results per @jsc_calloutid				**
**		 0 = failed.					**
**		>0 = succeeded.					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=6)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (6, 0,
"LOAD CALLOUT$",
"DECLARE @jsc_calloutid int,
	@jsc_sjobid int,
	@jsc_condid int,
	@jsc_bsqlid int,
	@jsc_esqlid int,
	@jsc_jtype int,
	@jsc_state char(2),
	@jsc_start datetime,
	@jsc_timeout int,
	@jsc_modified int
SELECT @jsc_calloutid=max(jsc_calloutid) FROM js_callouts WHERE  %s %d
SELECT
	@jsc_calloutid=jsc_calloutid,
	@jsc_sjobid=jsc_sjobid,
	@jsc_condid=jsc_condid,
	@jsc_bsqlid=jsc_bsqlid,
	@jsc_esqlid=jsc_esqlid,
	@jsc_jtype=jsc_jtype,
	@jsc_state=jsc_state,
	@jsc_start=jsc_start,
	@jsc_timeout=jsc_timeout,
	@jsc_modified=jsc_modified
FROM js_callouts
WHERE jsc_calloutid = @jsc_calloutid
PRINT "":1: %%1! %%2! %%3! %%4! %%5! %%6! %%7! %%8! %%9! %%10!"",
	@jsc_calloutid, @jsc_sjobid, @jsc_condid, @jsc_bsqlid, @jsc_esqlid,
	@jsc_jtype, @jsc_state, @jsc_start, @jsc_timeout, @jsc_modified
$")
go
print ": js_seqsql installed token  6 - LOAD CALLOUT"
go


/*****************************************************************
** needs attention as we can only do one record at a time.	**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=7)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (7, 0,
"LOAD JS_SCHEDULEDJOBS$",
"DECLARE @sjob_id int,
	@sjob_job_id int,
	@sjob_sched_id int,
	@sjob_update int,
	@sjob_enable smallint,
	@sjob_properties int,
	@sjob_created datetime,
	@sjob_timeout_value int,
	@sjob_owner varchar(30),
	@sjob_server varchar(30),
	@sjob_locale varchar(30),
	@sjob_name varchar(64),
	@sjob_uproperties varchar(128)

	SELECT @sjob_id=sjob_id,
		@sjob_job_id=sjob_job_id,
		@sjob_sched_id=sjob_sched_id,
		@sjob_update=sjob_update,
		@sjob_enable=sjob_enable,
		@sjob_properties=sjob_properties,
		@sjob_created=sjob_created,
		@sjob_timeout_value=sjob_timeout_value,
		@sjob_owner=sjob_owner,
		@sjob_server=sjob_server,
		@sjob_locale=sjob_locale,
		@sjob_name=sjob_name,
		@sjob_uproperties=sjob_uproperties
	FROM   js_scheduledjobs
	WHERE  sjob_id %s %d

	PRINT "":3: %%1! %%2! %%3! %%4! %%5! %%6! %%7! %%8! %%9! %%10! %%11! %%12! %%13!"",
		@sjob_id, @sjob_job_id, @sjob_sched_id, @sjob_update, @sjob_enable,
		@sjob_properties, @sjob_created, @sjob_timeout_value, @sjob_owner,
		@sjob_server, @sjob_locale, @sjob_name, @sjob_uproperties
$")
go
print ": js_seqsql installed token  7 - LOAD JS_SCHEDULEDJOBS"
go


/*****************************************************************
** extract data from js_schedules per sched_id			**
** data resulting is provided to js__calccallouts computing	**
** next callout time.						**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=8)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (8, 0,
"GET JS_SCHEDULES$",
"DECLARE @s_id int,
	@s_update int,
	@s_type int,
	@s_properties int,
	@s_owner char(30),
	@s_created datetime,
	@s_interval int,
	@s_interval_units char(1),
	@s_startdate datetime,
	@s_starttime datetime,
	@s_enddate datetime,
	@s_endtime datetime,
	@s_days smallint,
	@s_dates int,
	@s_name char(64),
	@s_description char(128),
	@s_uproperties char(128),
	@s_uinterval char(32),
	@s_udays char(128),
	@s_udates char(128)

	SELECT @s_id = sched_id,
	       @s_update = sched_update,
	       @s_type = sched_type,
	       @s_properties = sched_properties,
	       @s_owner = sched_owner,
	       @s_created = sched_created,
	       @s_interval = sched_interval,
	       @s_interval_units = sched_interval_units,
	       @s_startdate = sched_startdate,
	       @s_starttime = sched_starttime,
	       @s_enddate = sched_enddate,
	       @s_endtime = sched_endtime,
	       @s_days = sched_days,
	       @s_dates = sched_dates,
	       @s_name = sched_name,
	       @s_description = sched_description,
	       @s_uproperties = sched_uproperties,
	       @s_uinterval = sched_uinterval,
	       @s_udays = sched_udays,
	       @s_udates = sched_udates
	FROM   js_schedules sd,
	       js_scheduledjobs sj
	WHERE  sj.sjob_id = %d AND sj.sjob_sched_id=sd.sched_id

	PRINT "":4: %%1! %%2! %%3! %%4! %%5! %%6! %%7! %%8! %%9! %%10! %%11! %%12! %%13! %%14! %%15! %%16! %%17! %%18! %%19! %%20!"",
		@s_id, @s_update, @s_type, @s_properties,
		@s_owner, @s_created, @s_interval, @s_interval_units,
		@s_startdate, @s_starttime, @s_enddate, @s_endtime,
		@s_days, @s_dates, @s_name, @s_description,
		@s_uproperties, @s_uinterval, @s_udays, @s_udates
$")
go
print ": js_seqsql installed token  8 - GET JS_SCHEDULES"
go


/*****************************************************************
**	Update "js_callouts" when new callout calculations	**
**	are performed.						**
**								**
**	arguments:						**
**		jsc_start -> DATES_SHORT (MM/DD/CCYY hh:mm)	**
**		jsc_modified -> 0=not modified, 1=modified	**
**		jsc_calloutid -> Callout Identifier		**
**		jsc_newcalloutid -> New Callout Identifier	**
**								**
**	returns: rows affected					**
**		0 = failed					**
**		1 = succeeded					**
**	       >1 = failed					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=9)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (9, 0,
"SET JSC_START$",
"UPDATE	js_callouts
	SET	jsc_state='W',
		jsc_start='%s',
		jsc_modified=%d,
		jsc_calloutid=%d
	WHERE	jsc_calloutid=%d

	PRINT	"":i: %%1!"", @@rowcount
$")
go
print ": js_seqsql installed token  9 - SET JSC_START"
go


/*****************************************************************
** Retrieve the highest jsh_exid from js_history		**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=10)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (10, 0,
"GET MAX JSH_EXID$",
"DECLARE @value int
	SELECT @value = MAX(jsc_calloutid)
	FROM   js_callouts
	IF @value is NULL SELECT @value=MAX(jsh_exid) FROM js_history
	IF @value is NULL SELECT @value=0

	PRINT  "":i: %%1!"", @value
$")
go
print ": js_seqsql installed token 10 - GET MAX JSH_EXID"
go


/*****************************************************************
** get the DCL entry for SYB_JSAGENT from master..sysservers	**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=11)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (11, 0,
"GET SYB_JSAGENT$",
"DECLARE @value varchar(255)
	SELECT @value=srvnetname
	FROM master..sysservers
	WHERE srvname='SYB_JSAGENT'

	PRINT "":s: %%1!"", @value
$")
go
print ": js_seqsql installed token 11 - GET SYB_JSAGENT"
go


/*****************************************************************
**	Update js_history mark RUNNABLE state			**
**								**
**	results per @@rowcount:					**
**		 0 = failed.					**
**		 1 = succeeded.					**
**		 2 = busy.					**
**		>1 = failed too many rows updated.		**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=12)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (12, 0,
"SET RUNNABLE$",
"DECLARE @exid int,
@sjobid int,
@sjob_job_id int,
@jsh_user_run varchar(30),
@jsh_user_req varchar(30),
@sjob_properties int,
@rows int,
@state varchar(2)
SELECT @exid=%d, @sjobid=%d

SELECT @jsh_user_req=jsc_user_req
FROM	js_callouts
WHERE	jsc_calloutid=@exid

IF @jsh_user_req is NULL
	SELECT @jsh_user_req=sjob_owner, @sjob_job_id=sjob_job_id
	FROM	js_scheduledjobs
	WHERE	sjob_id=@sjobid
ELSE
	SELECT @sjob_job_id=sjob_job_id
	FROM	js_scheduledjobs
	WHERE	sjob_id=@sjobid

SELECT @jsh_user_run=job_owner, @sjob_properties=job_properties
FROM	js_jobs
WHERE	job_id=@sjob_job_id

IF ((@sjob_properties & 2) = 0)
BEGIN
	SELECT	@jsh_user_run=@jsh_user_req
END

SELECT	@state='R1'
IF EXISTS (SELECT 1 from js_history WHERE jsh_sjobid=@sjobid AND jsh_state IN ('R1','R2') AND (@sjob_properties & 1) = 0)
	SELECT	@state='B'

BEGIN TRAN
	INSERT	js_history (
		jsh_exid,
		jsh_sjobid,
		jsh_condid,
		jsh_jobname,
		jsh_schedname,
		jsh_jtype,
		jsh_state,
		jsh_jobstart,
		jsh_user_run,
		jsh_user_req)
	SELECT	@exid,
		jc.jsc_sjobid,
		jc.jsc_condid,
		jo.job_name,
		js.sched_name,
		jc.jsc_jtype,
		@state,
		jc.jsc_start,
		@jsh_user_run,
		@jsh_user_req
	FROM	js_callouts jc,
		js_scheduledjobs jj,
		js_schedules js,
		js_jobs jo
	WHERE	jc.jsc_calloutid=@exid AND jj.sjob_id=jc.jsc_sjobid AND js.sched_id=jj.sjob_sched_id AND jo.job_id=jj.sjob_job_id

	SELECT	@rows=@@rowcount
	IF 	@rows=1
	BEGIN
		UPDATE	js_callouts 
		SET
			jsc_state='W',
			jsc_modified=1
		WHERE	jsc_calloutid=@exid

		SELECT	@rows=@@rowcount

		IF @state = 'B' SELECT @rows = 2
		PRINT  "":i: %%1!"", @rows
		COMMIT TRAN
	END
	ELSE
	BEGIN
		PRINT  "":i: %%1!"", @rows
		ROLLBACK TRAN
	END
$")
go
print ": js_seqsql installed token 12 - SET RUNNABLE"
go


/*****************************************************************
**	Update jsh_state to 'C2' 				**
**		on jsh_exid where jsh_state 'C1'		**
**								**
**	results per @@rowcount:					**
**		 0 = failed.					**
**		 1 = succeeded.					**
**		>1 = failed to many rows updated.		**
**								**
**	HACK transition 2 could already have happened		**
**	this is a race condition in the Agent			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=13)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (13, 0,
"SET COMPLETED$",
"DECLARE @exid int,
@rows int
SELECT	@exid=%d

BEGIN	TRAN
	UPDATE	js_history
	SET
		jsh_state='C2'
	WHERE	jsh_exid=@exid AND (jsh_state='C1' OR jsh_state='C2')

	SELECT	@rows=@@rowcount
	PRINT	"":i: %%1!"", @rows
	IF	@rows=1
	BEGIN
		COMMIT TRAN
	END
	ELSE
	BEGIN
		ROLLBACK TRAN
	END
$")
go
print ": js_seqsql installed token 13 - SET COMPLETED"
go


/*****************************************************************
**	Update jsh_state to 'T2' 				**
**		on jsh_exid where jsh_state 'T1'		**
**								**
**	results per @@rowcount:					**
**		 0 = failed.					**
**		 1 = succeeded.					**
**		>1 = failed to many rows updated.		**
**								**
**	HACK transition 2 could already have happened		**
**	this is a race condition in the Agent			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=14)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (14, 0,
"SET TERMINATED$",
"DECLARE @exid int,
@rows int
SELECT	@exid=%d

BEGIN	TRAN
	UPDATE	js_history
	SET
		jsh_state='T2'
	WHERE	jsh_exid=@exid AND (jsh_state='T1' OR jsh_state='T2')

	SELECT	@rows=@@rowcount
	PRINT	"":i: %%1!"", @rows
	IF	@rows=1
	BEGIN
		COMMIT TRAN
	END
	ELSE
	BEGIN
		ROLLBACK TRAN
	END
$")
go
print ": js_seqsql installed token 14 - SET TERMINATED"
go


/*****************************************************************
**	Update jsh_state to 'X2' 				**
**		on jsh_exid where jsh_state 'X1'		**
**								**
**	results per @@rowcount:					**
**		 0 = failed.					**
**		 1 = succeeded.					**
**		>1 = failed to many rows updated.		**
**								**
**	HACK transition 2 could already have happened		**
**	this is a race condition in the Agent			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=15)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (15, 0,
"SET EXPIRED$",
"DECLARE @exid int,
@rows int
SELECT	@exid=%d

BEGIN	TRAN
	UPDATE	js_history
	SET
		jsh_state='X2'
	WHERE	jsh_exid=@exid AND (jsh_state='X1' OR jsh_state='X2')

	SELECT	@rows=@@rowcount
	PRINT	"":i: %%1!"", @rows
	IF	@rows=1
	BEGIN
		COMMIT TRAN
	END
	ELSE
	BEGIN
		ROLLBACK TRAN
	END
$")
go
print ": js_seqsql installed token 15 - SET EXPIRED"
go


/*****************************************************************
**	JS Agent launch command strings				**
**		-p = port to listen on.				**
**		-n = hostname.					**
**		-t = threads to enable.				**
**		-l = tracing level.				**
**		-v = report version.				**
**		-e = path to errlog file.			**
**		-i = path to DCL directory.			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=16)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (16, 4, "EXEC JSAGENT$",
"%s -p %s -n %s -t 4 -l %d -v -e %s -i %s > /dev/null 2>&1$")
go
print ": js_seqsql installed token 16 - EXEC JSAGENT"
go
/*****************************************************************
**	JS Agent (DEBUG) launch command strings			**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=17)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (17, 4, "EXEC DIAGJSAG$",
"%s -p %s -n %s -t 4 -l %d -v -e %s -i %s > /dev/null 2>&1$")
go
print ": js_seqsql installed token 17 - EXEC DIAGJSAG"
go


/*****************************************************************
**	Insert a new Job into js_callouts			**
**	results per @@rowcount:					**
**		 0 = disabled.					**
**		 1 = succeeded.					**
**		>1 = failed to many rows inserted.		**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=18)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (18, 0,
"INSERT CALLOUT$",
"DECLARE @jobid int, @calloutid int, @suid int, @user varchar(32)
	SELECT @jobid=%d, @calloutid=%d, @suid=%d
		IF EXISTS (
			SELECT 1 from js_callouts
			WHERE  @calloutid=jsc_calloutid
		)
	BEGIN
		PRINT	"":i: %%1!"", 2
	END
	ELSE
	BEGIN
		IF @suid != 0
			SELECT @user=suser_name(@suid)
		ELSE
			SELECT @user=NULL
		INSERT INTO js_callouts (
			jsc_calloutid,
			jsc_sjobid,
			jsc_condid,
			jsc_bsqlid,
			jsc_esqlid,
			jsc_jtype,
			jsc_state,
			jsc_start,
			jsc_timeout,
			jsc_modified,
			jsc_user_req
		)
		SELECT	@calloutid, sj.sjob_id, 0, NULL, NULL, jd.job_type, 'W', NULL, sj.sjob_timeout_value, 1, @user
			FROM	js_scheduledjobs sj, js_jobs jd
			WHERE	sj.sjob_id=@jobid AND sj.sjob_job_id=jd.job_id
		PRINT	"":i: %%1!"", @@rowcount
	END
$")
go
print ": js_seqsql installed token 18 - INSERT CALLOUT"
go


/*****************************************************************
**	Delete a callout from js_callouts			**
**	results per @@rowcount:					**
**		 0 = failed.					**
**		 1 = succeeded.					**
**		>1 = failed.					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=19)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (19, 0,
"DELETE CALLOUT$",
"DECLARE @sjobid int, @calloutid int
SELECT @sjobid=%d, @calloutid=%d
IF (@calloutid = 0)
	DELETE	js_callouts
	WHERE	jsc_sjobid = @sjobid
ELSE
	DELETE	js_callouts
	WHERE	jsc_sjobid = @sjobid AND jsc_calloutid = @calloutid

PRINT	"":i: %%1!"", @@rowcount
$")
go
print ": js_seqsql installed token 19 - DELETE CALLOUT"
go


/*****************************************************************
**	Add SYB_JSTASK to sysservers				**
**	results per @@rowcount:					**
**		 0 = failed.					**
**		 1 = succeeded.					**
*****************************************************************/
if exists (select ssql_sid from js_seqsql where ssql_sid=20)
delete from js_seqsql where ssql_sid=20
go

if not exists (select ssql_sid from js_seqsql where ssql_sid=20)

IF EXISTS (SELECT 1 FROM master..syscolumns where name like 'srvstatus2')
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (20, 0,
"ADD JSTASK$",
"IF NOT EXISTS (
	SELECT 1 FROM master..sysservers
	WHERE srvname = 'SYB_JSTASK'
 )
	BEGIN
		DECLARE @status int
		SELECT @status = number
		FROM master.dbo.spt_values
		WHERE type = 'A' AND name = 'rpc security model A'
		INSERT master..sysservers
		SELECT isnull(max(srvid),0)+1 ,@status ,'SYB_JSTASK' ,'%s' ,7 ,NULL ,1000, 0
		FROM master..sysservers
	END
$")
ELSE
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (20, 0,
"ADD JSTASK$",
"IF NOT EXISTS (
	SELECT 1 FROM master..sysservers
	WHERE srvname = 'SYB_JSTASK'
 )
	BEGIN
		DECLARE @status int
		SELECT @status = number
		FROM master.dbo.spt_values
		WHERE type = 'A' AND name = 'rpc security model A'
		INSERT master..sysservers
		SELECT isnull(max(srvid),0)+1 ,@status ,'SYB_JSTASK' ,'%s' ,7 ,NULL ,1000, 0
		FROM master..sysservers
	END
$")
go
print ": js_seqsql installed token 20 - ADD JSTASK"
go


/*****************************************************************
**	Update a Job data in js_callouts			**
**	results per @@rowcount:					**
**		 0 = failed.					**
**		 1 = succeeded.					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=21)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (21, 0,
"UPDATE CALLOUT$",
"DECLARE @jobid int, @calloutid int, @newcalloutid int
	SELECT @jobid=%d, @calloutid=%d, @newcalloutid=%d
	IF NOT EXISTS (
		SELECT 1 from js_callouts
		WHERE  @jobid=jsc_sjobid AND @calloutid=jsc_calloutid
	)
	BEGIN
		PRINT	"":i: %%1!"", @@rowcount
	END
	ELSE
	BEGIN
		UPDATE js_callouts 
		SET
			jsc_condid=0,
			jsc_bsqlid=NULL,
			jsc_esqlid=NULL,
			jsc_jtype=jd.job_type,
			jsc_state='W',
			jsc_start=NULL,
			jsc_timeout=js.sjob_timeout_value,
			jsc_modified=1,
			jsc_calloutid=@newcalloutid
		FROM
			js_callouts jc, js_scheduledjobs js, js_jobs jd
		WHERE
			jc.jsc_sjobid=@jobid AND jc.jsc_calloutid=@calloutid AND
			js.sjob_id=jc.jsc_sjobid AND js.sjob_job_id=jd.job_id
		PRINT	"":i: %%1!"", @@rowcount
	END
$")
go
print ": js_seqsql installed token 21 - UPDATE CALLOUT"
go



/*****************************************************************
**	Update jsc_state within "js_callouts" 			**
**								**
**	arguments:						**
**		jsc_state -> 'W', 'R' or 'Q'			**
**		jsc_modified -> 0=not modified, 1=modified	**
**		jsc_calloutid -> Callout Identifier		**
**								**
**	returns: rows affected					**
**		0 = failed					**
**		1 = succeeded					**
**	       >1 = failed					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=22)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (22, 0,
"SET JSC_STATE$",
"UPDATE	js_callouts
	SET	jsc_state='%s',
		jsc_modified=%d,
		jsc_calloutid=%d
	WHERE	jsc_calloutid=%d

	PRINT	"":i: %%1!"", @@rowcount
$")
go
print ": js_seqsql installed token 22 - SET JSC_STATE"
go

/*****************************************************************
**	Update jsh_state after uncontrolled shutdown		**
**								**
**	R1/R2 -> T2						**
**	T1    -> T2						**
**	X1    -> X2						**
**	C1    -> C2						**
**								**
**	returns: 						**
**		1 = succeeded					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=23)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (23, 0,
"CLEAN JSH_STATE$",
"UPDATE	js_history SET	jsh_state='T2', jsh_exit_code=3
	WHERE	(jsh_state='T1' OR jsh_state='R1' OR jsh_state='R2') AND jsh_exit_code=0
 UPDATE	js_history SET	jsh_state='T2' WHERE	jsh_state='T1' OR jsh_state='R1' OR jsh_state='R2'
 UPDATE	js_history SET	jsh_state='X2' WHERE	jsh_state='X1'
 UPDATE	js_history SET	jsh_state='C2' WHERE	jsh_state='C1'

	PRINT	"":i: %%1!"", 1
$")
go
print ": js_seqsql installed token 23 - CLEAN JSH_STATE"
go

/*****************************************************************
**	Update sched_expired after running a none repeating job **
**								**
**	returns: 						**
**		1 = succeeded					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=24)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (24, 0,
"EXPIRE SCHEDULE$",
"DECLARE @sched_id int
 SELECT @sched_id=sjob_sched_id FROM js_scheduledjobs WHERE sjob_id = %d
 UPDATE	js_schedules SET sched_expired=1 WHERE sched_id=@sched_id

	PRINT	"":i: %%1!"", 1
$")
go
print ": js_seqsql installed token 24 - EXPIRE SCHEDULE"
go

/*****************************************************************
**	Lock / Unlock jstask login 				**
**								**
**	returns: 						**
**		1 = succeeded					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=25)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (25, 0,
"UNLOCK JSTASK$",
"DECLARE @user varchar(30), @unlock varchar(30)
 SELECT @user='%s', @unlock='%s'
 IF @unlock = 'unlock'
 BEGIN
	IF exists (SELECT name FROM master..syslogins WHERE
			name = @user AND (status & 2) = 2)
		EXEC sp_locklogin @user, 'unlock'
 END
 ELSE
 BEGIN
	IF exists (SELECT name FROM master..syslogins WHERE
			name = @user AND (status & 2) != 2)
		EXEC sp_locklogin @user, 'lock'
 END
	PRINT	"":i: %%1!"", 1
$")
go
print ": js_seqsql installed token 25 - UNLOCK JSTASK"
go

/*****************************************************************
**	Check Arguments to js_wakeup				**
**								**
**	returns: 						**
**		0 = failed					**
**		1 = succeeded					**
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=26)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (26, 0,
"CHECK WAKEUP$",
"DECLARE @r int, @srid int, @adm int, @what varchar(30), @id int, @suid int, @act int, @own varchar(30)
 SELECT @r=0, @srid=NULL, @adm=0, @what='%s', @id=%d, @suid=%d, @act=%d
 IF patindex('%_role', @what) != 0
 BEGIN
	SELECT @srid=srid FROM master..syssrvroles WHERE name=@what
	SELECT @r=status FROM master..sysloginroles WHERE srid=@srid AND suid=@suid
	PRINT	"":i: %%1!"", @r
	RETURN
 END
 SELECT @srid=srid FROM master..syssrvroles WHERE name='js_admin_role'
 SELECT @adm=status FROM master..sysloginroles WHERE srid=@srid AND suid=@suid
 IF @adm=0
 BEGIN
	SELECT @srid=srid FROM master..syssrvroles WHERE name='sa_role'
	SELECT @adm=status FROM master..sysloginroles WHERE srid=@srid AND suid=@suid
 END
 SELECT @own=suser_name(@suid)
 IF @what='job_id'
	SELECT @r=1 FROM sybmgmtdb..js_jobs WHERE job_id=@id AND (@adm=1 OR job_owner=@own)
 ELSE IF @what='sched_id'
	SELECT @r=1 FROM sybmgmtdb..js_schedules WHERE sched_id=@id AND (@adm=1 OR sched_owner=@own)
 ELSE IF @what='sjobid'
	SELECT @r=1 FROM sybmgmtdb..js_scheduledjobs WHERE sjob_id=@id AND (@adm=1 OR sjob_owner=@own)
 ELSE IF @what='run_now'
	SELECT @r=1 FROM sybmgmtdb..js_scheduledjobs
	WHERE sjob_id=@id AND (@adm=1 OR sjob_owner=@own OR (sjob_properties & 64)=64)
 ELSE IF @what='runid'
	SELECT @r=1 FROM sybmgmtdb..js_history WHERE jsh_exid=@id AND (@adm=1 OR jsh_user_req=@own)
 ELSE IF @what='jobid'
 BEGIN
	SELECT @id=sjob_job_id FROM sybmgmtdb..js_scheduledjobs WHERE sjob_id=@id
	SELECT @r=1 FROM sybmgmtdb..js_jobs WHERE job_id=@id AND (@adm=1 OR job_owner=@own)
 END
 ELSE IF @what='schedid'
 BEGIN
	SELECT @id=sjob_sched_id FROM sybmgmtdb..js_scheduledjobs WHERE sjob_id=@id
	SELECT @r=1 FROM sybmgmtdb..js_schedules WHERE sched_id=@id AND (@adm=1 OR sched_owner=@own)
 END
 ELSE
	SELECT @r=0
 PRINT	"":i: %%1!"", @r
$")
go
print ": js_seqsql installed token 26 - CHECK WAKEUP"
go

/*****************************************************************
**	Check Arguments to js_wakeup				**
**								**
**	returns: 						**
**		1 = succeeded					**
**		2 = failed due to lack of js_callouts entry or  **
**                    invalid (0) sjob_id in js_callouts        **
**		3 = failed due to lack of js_scheduledjobs entry**
**                    or invalid (0) job_id in js_scheduledjobs **
**		4 = failed due to lack of js_jobs entry         **
**		5 = failed due to lack of js_schedules entry    **
*****************************************************************/
if not exists (select ssql_sid from js_seqsql where ssql_sid=27)
insert into js_seqsql (ssql_sid, ssql_type, ssql_name, ssql_sql)
values (27, 0,
"VERIFY CALLOUT$",
"DECLARE @r int, @exid int, @sjobid int, @jobid int, @schedid int
 SELECT @r=1, @exid=%d, @sjobid=0, @jobid=0, @schedid=0
 SELECT @sjobid=jsc_sjobid FROM js_callouts WHERE jsc_calloutid=@exid 
 SELECT @jobid=sjob_job_id, @schedid=sjob_sched_id FROM js_scheduledjobs WHERE sjob_id=@sjobid
 IF @sjobid=0
	select @r=2
 ELSE IF @jobid=0
	select @r=3
 ELSE IF NOT EXISTS (SELECT 1 FROM js_jobs where job_id=@jobid)
	select @r=4
 ELSE IF NOT EXISTS (SELECT 1 FROM js_schedules where sched_id=@schedid)
	select @r=5
 PRINT	"":i: %%1!"", @r
$")
go
print ": js_seqsql installed token 27 - VERIFY CALLOUT"
go

/*****************************************************************
** We're done and have our sequencer code installed		**
*****************************************************************/
print "Sequencer code installed in js_seqsql ..."
go
go
dump transaction sybmgmtdb with truncate_only
go
--
-- Internal JobScheduler stored procdure
--
-- Warning this procedure is not a published interface, do not use it.
--
if exists (select name from sysobjects where name = 'sp_js_wakeup')
	drop proc sp_js_wakeup
go
create proc sp_js_wakeup(@cmd varchar(64), @id int)
as
begin
	declare @retstatus int
	select  @retstatus=js_wakeup(@cmd, @id)
	return  @retstatus
end
go
go
if exists (select name from sysobjects where name = 'sp_jsversion')
	drop proc sp_jsversion
go
--
-- Internal JobScheduler stored procdure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- returns the version of the API provided by the JobScheduler stored procedures
--
create proc sp_jsversion as
begin
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select "15.0.0.0"
	return 0
end
go
grant execute on sp_jsversion to js_user_role
go
grant execute on sp_jsversion to js_admin_role
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_js_check_id')
	drop proc sp_js_check_id
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Validates a job scheduler name or id in the given table
-- @name_id     the name or id to validate
-- @cmd         0: allow only names, 1: only ids >=1, 2: allow either, 3: only ids >=0
-- @table       check that the name or id exists in the table.
-- @return_id   return the id value, rather than 0 for a name argument
--
-- Returns <0 on error,
-- the integer value of id when name_id is an id
-- the integer value of id when name_id is a name and return=1
-- otherwise returns 0 when name_id is a name
--
--
create proc sp_js_check_id (
        @name_id        univarchar(64),
        @cmd            int,
        @table          varchar(64)   = NULL,
        @return_id      int           = NULL,
	@user		varchar(30)   = NULL,
	@is_admin	int           = NULL
)
as
begin
	declare	@i1 int, @err int, @rows int, @len int, @js_id int
	declare @int_limit univarchar(10)
	declare @temp_id univarchar(64)

	select @temp_id = rtrim(@name_id)
	select @temp_id = ltrim(@temp_id)
	if @temp_id is NULL
		-- 19048 'Procedure %1!, parameter %2!, was not supplied, NULL or empty.'
		return -19048
	--
	-- A name is anything that doesn't begin with a digit
	--
	if substring(@temp_id, 1, 1) not like '[0-9]'
	begin
		if @cmd = 1 or @cmd = 3
			-- 19049 'Procedure %1!, parameter %2!, requires an id value, not a name.'
			return -19049
		--
		-- if table is supplied, check the name exists in the given table
		--
		if @table is NULL
			return 0
-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
-- 19051 'Procedure %1!, parameter %2!, the specified schedule does not exist.'
-- 19052 'Procedure %1!, parameter %2!, the specified scheduled job does not exist.'
-- 19097 'Procedure %1!, %2! is a non-unique name for a scheduledjob, job or schedule, the id value must be used.'
-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
		-- support unique name per user
		if @table = 'sjob'
		begin
			select @js_id=sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_name=@temp_id and sjob_owner = suser_name()
			select @err=@@error, @rows=@@rowcount
			if @err = 0 and @rows = 0
			begin
				select @js_id=sjob_id from sybmgmtdb..js_scheduledjobs
					where sjob_name=@temp_id and (sjob_properties & 64) = 64
				select @err=@@error, @rows=@@rowcount
			end
			if @err = 0 and @rows = 0
			begin
				select @js_id=sjob_id from sybmgmtdb..js_scheduledjobs
					where sjob_name=@temp_id
				select @err=@@error, @rows=@@rowcount
				if @is_admin != 1 and @rows > 0	return -19083
			end
			if @js_id is NULL	return -19052
			if @rows > 1	return -19097
		end
		else if @table = 'job'
		begin
			select @js_id=job_id from sybmgmtdb..js_jobs
				where job_name=@temp_id and job_owner = suser_name()
			select @err=@@error, @rows=@@rowcount
			if @err = 0 and @rows = 0
			begin
				select @js_id=job_id from sybmgmtdb..js_jobs
					where job_name=@temp_id and (job_properties & 32) = 32
				select @err=@@error, @rows=@@rowcount
			end
			if @err = 0 and @rows = 0
			begin
				select @js_id=job_id from sybmgmtdb..js_jobs
					where job_name=@temp_id
				select @err=@@error, @rows=@@rowcount
				if @is_admin != 1 and @rows > 0	return -19083
			end
			if @js_id is NULL	return -19050
			if @rows > 1	return -19097
		end
		else if @table = 'sched'
		begin
			select @js_id=sched_id from sybmgmtdb..js_schedules
				where sched_name=@temp_id and sched_owner = suser_name()
			select @err=@@error, @rows=@@rowcount
			if @err = 0 and @rows = 0
			begin
				select @js_id=sched_id from sybmgmtdb..js_schedules
					where sched_name=@temp_id and (sched_properties & 32) = 32
				select @err=@@error, @rows=@@rowcount
			end
			if @err = 0 and @rows = 0
			begin
				select @js_id=sched_id from sybmgmtdb..js_schedules
					where sched_name=@temp_id
				select @err=@@error, @rows=@@rowcount
				if @is_admin != 1 and @rows > 0 return -19083
			end
			if @js_id is NULL	return -19051
			if @rows > 1	return -19097
		end
		else if @table = 'sjob_'
		begin
			-- @temp_id is 'sjob_' + a number
			-- 19091 'Procedure %1!, %2! is not a valid name.'
			if substring(@temp_id, 1, 5) = 'sjob_'
				if patindex('%[^0-9]%', substring(@temp_id, 6, char_length(@temp_id) - 5)) <= 0
					return -19091
		end
		else if @table = 'job_'
		begin
			-- @temp_id is 'job_' + a number
			-- 19091 'Procedure %1!, %2! is not a valid name.'
			if substring(@temp_id, 1, 4) = 'job_'
				if patindex('%[^0-9]%', substring(@temp_id, 5, char_length(@temp_id) - 4)) <= 0
					return -19091
		end
		else if @table = 'sched_'
		begin
			-- @temp_id is 'sched_' + a number
			-- 19091 'Procedure %1!, %2! is not a valid name.'
			if substring(@temp_id, 1, 6) = 'sched_'
				if patindex('%[^0-9]%', substring(@temp_id, 7, char_length(@temp_id) - 6)) <= 0
					return -19091
		end
		else if @table = 'jtmpl_'
		begin
			-- @temp_id is 'jtmpl_' + a number
			-- 19091 'Procedure %1!, %2! is not a valid name.'
			if substring(@temp_id, 1, 6) = 'jtmpl_'
				if patindex('%[^0-9]%', substring(@temp_id, 7, char_length(@temp_id) - 6)) <= 0
					return -19091
		end
		else
		begin
			-- 19053 'Procedure %1!, parameter %2!, the specified table id name is not known.'
			return -19053
		end
		--
		-- if return_id return the js_id rather than the usual 0
		--
		if @return_id = 1
			return @js_id
		return 0
	end
	--
	--
	--
	if @cmd = 0
		-- 19054 'Procedure %1!, parameter %2!, requires a name, not an id value.'
		return -19054
	--
	-- Otherwise must be all digits
	--
	select @i1=patindex('%[^0-9]%', @temp_id)
	if @i1 > 0
		-- 19055 'Procedure %1!, parameter %2!, starts with a digit and also contains none digits.'
		return -19055
	select @int_limit='2147483647'
	select @len=isnull(char_length(@temp_id), 0)
	--
	-- remove any leading 0's
	--
	select @i1=patindex('%[1-9]%', @temp_id)
--print 'non 0 at pos %1!', @i1
	if @i1 is NULL or @i1 < 1
	begin
		if @cmd = 3
			return 0
		-- 19056 'Procedure %1!, parameter %2!, a zero value is not allowed.'
		return -19056
	end
--print 'substr %1! %2! %3!', @temp_id, @i1, @len
	select @temp_id=substring(@temp_id, @i1, @len - @i1 + 1)
--print 'temp_id %1!', @temp_id
	--
	-- Check for too many digits or greater than max int.
	--
	select @len=isnull(char_length(@temp_id), 0)
--print 'decimal number'
--print 'value length %1!', @len
	if (@len > 10) or (@len = 10 and @temp_id > @int_limit)
	begin
--print 'value > %1!', @int_limit
		-- 19057 'Procedure %1!, parameter %2!, cannot be larger than 2147483647.'
		return -19057
	end
--print 'value <= %1!', @int_limit
	--
	-- Convert it
	--
	select @i1=convert(int, @temp_id)
--print 'value %1!', @i1

	if @table is NULL
		return @i1
	--
	-- if table is supplied, check the id exists in the given table
	--
	if @table = 'job'
	begin
		select @js_id=job_id from sybmgmtdb..js_jobs
				where job_id=@i1 and job_owner = suser_name()
		select @err=@@error, @rows=@@rowcount
		if @err = 0 and @rows = 0
		begin
			select @js_id=job_id from sybmgmtdb..js_jobs
				where job_id=@i1 and (job_properties & 32) = 32
			select @err=@@error, @rows=@@rowcount
		end
		if @err = 0 and @rows = 0
		begin
			select @js_id=job_id from sybmgmtdb..js_jobs where job_id=@i1
			select @err=@@error, @rows=@@rowcount
			if @is_admin != 1 and @rows > 0	return -19083
		end
		if @js_id is NULL	return -19050
		if @rows > 1	return -19097
	end
	else if @table = 'sched'
	begin
		select @js_id=sched_id from sybmgmtdb..js_schedules
			where sched_id=@i1 and sched_owner = suser_name()
		select @err=@@error, @rows=@@rowcount
		if @err = 0 and @rows = 0
		begin
			select @js_id=sched_id from sybmgmtdb..js_schedules
				where sched_id=@i1 and (sched_properties & 32) = 32
			select @err=@@error, @rows=@@rowcount
		end
		if @err = 0 and @rows = 0
		begin
			select @js_id=sched_id from sybmgmtdb..js_schedules
				where sched_id=@i1
			select @err=@@error, @rows=@@rowcount
			if @is_admin != 1 and @rows > 0 return -19083
		end
		if @js_id is NULL	return -19051
		if @rows > 1	return -19097
	end
	else if @table = 'sjob'
	begin
		select @js_id=sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_id=@i1 and sjob_owner = suser_name()
		select @err=@@error, @rows=@@rowcount
		if @err = 0 and @rows = 0
		begin
			select @js_id=sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_id=@i1 and (sjob_properties & 64) = 64
			select @err=@@error, @rows=@@rowcount
		end
		if @err = 0 and @rows = 0
		begin
			select @js_id=sjob_id from sybmgmtdb..js_scheduledjobs
					where sjob_id=@i1
			select @err=@@error, @rows=@@rowcount
			if @is_admin != 1 and @rows > 0	return -19083
		end
		if @js_id is NULL	return -19052
		if @rows > 1	return -19097
	end
	else if @table = 'jsh'
	begin
		select @js_id=jsh_exid from sybmgmtdb..js_history
			where jsh_exid=@i1 and jsh_user_req = suser_name()
		select @err=@@error, @rows=@@rowcount
		if @err = 0 and @rows = 0
		begin
			select @js_id=jsh_exid from sybmgmtdb..js_history where jsh_exid=@i1
			select @err=@@error, @rows=@@rowcount
			if @is_admin != 1 and @rows > 0	return -19083
		end
		if @js_id is NULL
			-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
			return -19082
	end
	else if @table = 'jsout'
	begin
		select @js_id=jsout_exid from sybmgmtdb..js_output, sybmgmtdb..js_history
			where jsout_exid = jsh_exid and jsout_exid=@i1 and jsh_user_req = suser_name()
		select @err=@@error, @rows=@@rowcount
		if @err = 0 and @rows = 0
		begin
			select @js_id=jsout_exid from sybmgmtdb..js_output where jsout_exid=@i1
			select @err=@@error, @rows=@@rowcount
			if @is_admin != 1 and @rows > 0	return -19083
		end
		if @js_id is NULL
			-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
			return -19082
	end
	else if @table = 'jtmpl'
	begin
		select @js_id=jtmpl_id from sybmgmtdb..js_templates where jtmpl_id=@i1
		if @js_id is NULL
			-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
			return -19082
	end
	else
	begin
		-- 19053 'Procedure %1!, parameter %2!, the specified table name is not known.'
		return -19053
	end
	return @i1
end
go
if exists (select name from sysobjects where name = 'sp_js_check_id')
begin
	print 'Created sp_js_check_id'
end
go
if exists (select name from sysobjects where name = 'sp_js_dates2bits')
	drop proc sp_js_dates2bits
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Convert a comma or colon separated list of dates of the month into an int with
-- a bit set for each date (1-31). 32 is used to indicate the last date in any month.
-- 1st = bit1, 2nd = bit2, ... 31st = bit31, last day = bit 0
--
create proc sp_js_dates2bits (
        @idates         varchar(128)    = NULL,  -- incoming list of dates of the month
        @date_bits      int             output   -- outgoing int with bits set for each date
)
as
begin
	declare @ch char(1), @dates varchar(132)
	declare @startpos int, @len int, @i1 int, @total int, @num int, @num32 int

	if @idates is NULL
	begin
		select @date_bits=0
		return 0
	end

	-- reject anything which isn't just digits, commas, colons or spaces
	if patindex('%[^0-9,: ]%', @dates) > 0
	begin
		select @date_bits=0
		return 1
	end

	select @dates = ',' + @idates + ','
	select @len = isnull(char_length(@dates), 0), @startpos=1,@total=0,@num=0,@num32=0

	while @startpos <= @len
	begin
		select @ch=substring(@dates,@startpos,1)
        	select @startpos=@startpos  + 1
--	print 'ch %1!', @ch
		if @ch = ' ' continue
		if @ch = ',' or @ch = ':'
		begin
-- print 'Num %1!', @num
			-- start of a new number or end of the last
			if @num = 0 continue
			if @num = 31
				select @num32=1
			else
			begin
			select @i1=case @num
				when 1 then 2
				when 2 then 4
				when 3 then 8
				when 4 then 16
				when 5 then 32
				when 6 then 64
				when 7 then 128
				when 8 then 256
				when 9 then 512
				when 10 then 1024
				when 11 then 2048
				when 12 then 4096
				when 13 then 8192
				when 14 then 16384
				when 15 then 32768
				when 16 then 65536
				when 17 then 131072
				when 18 then 262144
				when 19 then 524288
				when 20 then 1048576
				when 21 then 2097152
				when 22 then 4194304
				when 23 then 8388608
				when 24 then 16777216
				when 25 then 33554432
				when 26 then 67108864
				when 27 then 134217728
				when 28 then 268435456
				when 29 then 536870912
				when 30 then 1073741824
				when 32 then 1
				end
				select @total=@total + @i1
--print 'i1 %1!, total %2!', @i1, @total
			end
			select @num=0
		end
		else
		begin
			-- build up the date number, ignoring leading zeros
			if @ch = '0' and @num = 0 continue
			select @num=@num * 10
			select @num=@num + convert(int, @ch)

			-- more than 32bits is an error
			if @num > 32
			begin
				select @date_bits=0
				return 1
			end
		end
	end
	-- handle setting top bit, by adding the @total (which is +ve)
	-- to the largest -ve int (database int)
	if @num32 = 1
	begin
		select @num32=-2147483648
		select @total=@num32 + @total
	end
	select @date_bits=@total
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_dates2bits')
begin
	print 'Created sp_js_dates2bits'
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_js_bits2dates')
	drop proc sp_js_bits2dates
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Convert an int of bits set for each date into a comma or colon separated list of dates of
-- the month.
-- 1st = bit1, 2nd = bit2, ... 31st = bit31, last day = bit 0
--
create proc sp_js_bits2dates (
        @date_bits      int             = NULL, -- incoming int with bits set for each date
        @odates         varchar(128)    output  -- outgoing list of dates of the month
)
as
begin
	declare @dates varchar(128)

	if @date_bits is NULL or @date_bits = 0
	begin
		select @odates=NULL
		return 0
	end
	select @dates=NULL
	if @date_bits & 0x00000002 = 0x00000002 select @dates=@dates + '1:'
	if @date_bits & 0x00000004 = 0x00000004 select @dates=@dates + '2:'
	if @date_bits & 0x00000008 = 0x00000008 select @dates=@dates + '3:'
	if @date_bits & 0x00000010 = 0x00000010 select @dates=@dates + '4:'
	if @date_bits & 0x00000020 = 0x00000020 select @dates=@dates + '5:'
	if @date_bits & 0x00000040 = 0x00000040 select @dates=@dates + '6:'
	if @date_bits & 0x00000080 = 0x00000080 select @dates=@dates + '7:'
	if @date_bits & 0x00000100 = 0x00000100 select @dates=@dates + '8:'
	if @date_bits & 0x00000200 = 0x00000200 select @dates=@dates + '9:'
	if @date_bits & 0x00000400 = 0x00000400 select @dates=@dates + '10:'
	if @date_bits & 0x00000800 = 0x00000800 select @dates=@dates + '11:'
	if @date_bits & 0x00001000 = 0x00001000 select @dates=@dates + '12:'
	if @date_bits & 0x00002000 = 0x00002000 select @dates=@dates + '13:'
	if @date_bits & 0x00004000 = 0x00004000 select @dates=@dates + '14:'
	if @date_bits & 0x00008000 = 0x00008000 select @dates=@dates + '15:'
	if @date_bits & 0x00010000 = 0x00010000 select @dates=@dates + '16:'
	if @date_bits & 0x00020000 = 0x00020000 select @dates=@dates + '17:'
	if @date_bits & 0x00040000 = 0x00040000 select @dates=@dates + '18:'
	if @date_bits & 0x00080000 = 0x00080000 select @dates=@dates + '19:'
	if @date_bits & 0x00100000 = 0x00100000 select @dates=@dates + '20:'
	if @date_bits & 0x00200000 = 0x00200000 select @dates=@dates + '21:'
	if @date_bits & 0x00400000 = 0x00400000 select @dates=@dates + '22:'
	if @date_bits & 0x00800000 = 0x00800000 select @dates=@dates + '23:'
	if @date_bits & 0x01000000 = 0x01000000 select @dates=@dates + '24:'
	if @date_bits & 0x02000000 = 0x02000000 select @dates=@dates + '25:'
	if @date_bits & 0x04000000 = 0x04000000 select @dates=@dates + '26:'
	if @date_bits & 0x08000000 = 0x08000000 select @dates=@dates + '27:'
	if @date_bits & 0x10000000 = 0x10000000 select @dates=@dates + '28:'
	if @date_bits & 0x20000000 = 0x20000000 select @dates=@dates + '29:'
	if @date_bits & 0x40000000 = 0x40000000 select @dates=@dates + '30:'
	if @date_bits & 0x80000000 = 0x80000000 select @dates=@dates + '31:'
	if @date_bits & 0x00000001 = 0x00000001 select @dates=@dates + '32:'

	if @dates is not NULL
		select @odates=substring(@dates, 1, char_length(@dates) - 1)
	else
		select @odates=NULL
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_bits2dates')
begin
	print 'Created sp_js_bits2dates'
end
go
go
if exists (select name from sysobjects where name = 'sp_js_days2bits')
	drop proc sp_js_days2bits
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Convert a comma or colon separated list of days of the week into
-- an int with a bit set for each day (1-7).
-- Sunday = bit0, Monday = bit1, ... Saturday = bit6
--
create proc sp_js_days2bits (
        @idays          varchar(128)    = NULL,  -- incoming list of days of the week
        @day_bits       int             output   -- outgoing int with bits set for each day
)
as
begin
	declare @ch char(1), @days varchar(132),  @day varchar(32)
	declare @err int, @rows int, @curpos int, @len int, @startpos int, @daylen int, @i1 int, @total int, @language int
	declare @mon varchar(32), @tue varchar(32), @wed varchar(32),
		@thu varchar(32), @fri varchar(32), @sat varchar(32), @sun varchar(32)

	if @idays is NULL
	begin
		select @day_bits=0
		return 0
	end

	--
	-- if not 'us_english' get the days from master..syslanguages
	--
	if @@language != 'us_english'
	begin
		--
		-- Check we haven't already cached the names
		--
		select @sun=jsday_sun, @mon=jsday_mon, @tue=jsday_tue, @wed=jsday_wed,
			@thu=jsday_thu, @fri=jsday_fri, @sat=jsday_sat 
			from sybmgmtdb..js_daynames where jsday_lang=@@language
		if @@rowcount = 0
		begin
			select @days=days from master..syslanguages where name = @@language
			select @days= ',' + @days + ','
			select @len=isnull(char_length(@days),0),@curpos=1,@startpos=0,@total=0
	
			while @curpos <= @len
			begin
				select @ch=substring(@days,@curpos,1)
				if @ch = ',' or @ch = ':'
				begin
					-- start of a new day or end of the last
					if @startpos = 0
					begin
						select @curpos=@curpos + 1
						continue
					end
					-- calculate and check the substring length
					select @daylen=@curpos - @startpos
					if @daylen > 32
						select @daylen=32

					select @day=lower(substring(@days, @startpos, @daylen))
					select @total=@total + 1
-- print 'start %1!, end %2!, day %3!  %4!', @startpos, @curpos, @total, @day
					select @day=rtrim(@day)
					select @day=ltrim(@day)
					-- syslanguages is M,T,W,T,F,S,S
					if @total = 1 select @mon=@day
					if @total = 2 select @tue=@day
					if @total = 3 select @wed=@day
					if @total = 4 select @thu=@day
					if @total = 5 select @fri=@day
					if @total = 6 select @sat=@day
					if @total = 7 select @sun=@day

					select @startpos=0
				end
				else if @ch != ' '
				begin
					-- not a space or comma, remember the start of a new day
					if @startpos = 0
					begin
						select @startpos=@curpos
					end
				end
				select @curpos=@curpos + 1
			end
			-- Check all is okay
			if @mon is NULL or @tue is NULL or @wed is NULL or @thu is NULL
				or @fri is NULL or @sat is NULL or @sun is NULL
			begin
				select @language=0
			end
			else
			begin
				--
				-- cache the days of the week
				--
				if exists (select jsday_lang from sybmgmtdb..js_daynames where jsday_lang = @@language)
				begin
					update sybmgmtdb..js_daynames set jsday_lang=@@language, jsday_sun=@sun, jsday_mon=@mon,
						jsday_tue=@tue, jsday_wed=@wed, jsday_thu=@thu, jsday_fri=@fri, jsday_sat=@sat
					where jsday_lang=@@language
					select @err=@@error
				end
				else
				begin
					insert into sybmgmtdb..js_daynames (jsday_lang, jsday_sun, jsday_mon, jsday_tue,
						jsday_wed, jsday_thu, jsday_fri, jsday_sat)
						values (@@language, @sun, @mon, @tue, @wed, @thu, @fri, @sat )
					select @err=@@error
				end
				if @err != 0
				begin
					select @language=0
				end
				else
				begin
					select @language=1
				end
			end
		end
	end
	else select @language=0
	--
	-- Process the list of comma separated days of the week
	--
	select @days = ',' + @idays + ','
	select @len = isnull(char_length(@days),0),@curpos=1,@startpos=0,@total=0

	while @curpos <= @len
	begin
		select @ch=substring(@days,@curpos,1)
		if @ch = ',' or @ch = ':'
		begin
			-- start of a new day or end of the last
			if @startpos = 0
			begin
				select @curpos=@curpos + 1
				continue
			end
			-- calculate and check the substring length
			select @daylen=@curpos - @startpos
			if @daylen > 32
			begin
				select @day_bits=0
				return 1
			end
			select @day=lower(substring(@days, @startpos, @daylen))
-- print 'start %1!, end %2!, day %3!', @startpos, @curpos, @day
			--
			-- try days in the locale first
			--
			select @i1=0
			if @language = 1
			begin
				select @i1=case @day
					when @sun then 1
					when @mon then 2
					when @tue then 4
					when @wed then 8
					when @thu then 16
					when @fri then 32
					when @sat then 64
					else 0
					end
			end
			--
			-- then try us_english
			--
			if @i1 = 0
			begin
				select @i1=case @day
					when 'sun' then 1  when 'sunday'    then 1
					when 'mon' then 2  when 'monday'    then 2
					when 'tue' then 4  when 'tuesday'   then 4
					when 'wed' then 8  when 'wednesday' then 8
					when 'thu' then 16 when 'thursday'  then 16
					when 'fri' then 32 when 'friday'    then 32
					when 'sat' then 64 when 'saturday'  then 64
					else 0
					end
			end
			--
			-- bad day of the week or we didn't get the locale days
			--
			if @i1 = 0
			begin
				return 1
			end
			select @total=@total + @i1
-- print 'i1 %1!, total %2!', @i1, @total
			select @startpos=0
		end
		else if @ch != ' '
		begin
			-- not a space or comma, remember the start of a new day
			if @startpos = 0
			begin
				select @startpos=@curpos
			end
		end
		select @curpos=@curpos + 1
	end
	select @day_bits=@total
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_days2bits')
begin
	print 'Created sp_js_days2bits'
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_js_bits2days')
	drop proc sp_js_bits2days
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Convert an int with a bit set for each day (1-7) into a comma or colon
-- separated list of days of the week
-- Sunday = bit0, Monday = bit1, ... Saturday = bit6
--
create proc sp_js_bits2days (
        @day_bits       int             = NULL,  -- incoming int with bits set for each day
        @odays          varchar(128)    output   -- outgoing list of days of the week
)
as
begin
	declare @days varchar(132)
	declare @err int, @rows int
	declare @mon varchar(32), @tue varchar(32), @wed varchar(32),
		@thu varchar(32), @fri varchar(32), @sat varchar(32), @sun varchar(32)

	if @day_bits is NULL or @day_bits = 0
	begin
		select @odays = NULL
		return 0
	end
	if @day_bits < 0 or @day_bits >= 128
	begin
		select @odays = NULL
		return -1
	end
	--
	-- if not 'us_english' get the days from master..syslanguages
	--
	if @@language != 'us_english'
	begin
		--
		-- Check we haven't already cached the names
		--
		select @sun=jsday_sun, @mon=jsday_mon, @tue=jsday_tue, @wed=jsday_wed,
			@thu=jsday_thu, @fri=jsday_fri, @sat=jsday_sat 
			from sybmgmtdb..js_daynames where jsday_lang=@@language
		if @@rowcount = 0
		begin
			exec sp_js_days2bits @idays='Monday', @day_bits=@err output

			select @sun=jsday_sun, @mon=jsday_mon, @tue=jsday_tue, @wed=jsday_wed,
				@thu=jsday_thu, @fri=jsday_fri, @sat=jsday_sat 
				from sybmgmtdb..js_daynames where jsday_lang=@@language
		end
		-- Check all is okay
		if @@rowcount = 0
			select @mon = NULL
		else if @mon is NULL or @tue is NULL or @wed is NULL or @thu is NULL
				or @fri is NULL or @sat is NULL or @sun is NULL
			select @mon = NULL
	end
	else select @mon = NULL
	--
	if @mon is NULL
		select @mon='monday', @tue='tuesday', @wed='wednesday', @thu='thursday',
			@fri='friday', @sat='saturday', @sun='sunday'
	select @days=NULL
	if @day_bits &  1 =  1 select @days=@days + @sun + ':'
	if @day_bits &  2 =  2 select @days=@days + @mon + ':'
	if @day_bits &  4 =  4 select @days=@days + @tue + ':'
	if @day_bits &  8 =  8 select @days=@days + @wed + ':'
	if @day_bits & 16 = 16 select @days=@days + @thu + ':'
	if @day_bits & 32 = 32 select @days=@days + @fri + ':'
	if @day_bits & 64 = 64 select @days=@days + @sat + ':'
	if @days is not NULL
		select @odays=substring(@days, 1, char_length(@days) - 1)
	else
		select @odays=NULL
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_bits2days')
begin
	print 'Created sp_js_bits2days'
end
go
go
if exists (select name from sysobjects where name = 'sp_js_getkey')
	drop proc sp_js_getkey
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Allocates the next key value for a job scheduler table.
--
--
create proc sp_js_getkey (
        @js_keyname     varchar(64)
)
as
begin
	declare @err int, @rows int, @js_id int
	--
	-- lookup the js_keyname
	--
	if not exists (select jskey_id from sybmgmtdb..js_keys where jskey_name = @js_keyname)
	begin
		-- 19058  'Procedure %1!, jskey_name %2! unable to allocate a new id.'
		return -19058
	end
	--
	-- Generate the next id
	--
	begin tran sp_js_getkey
	save tran get_key
	update sybmgmtdb..js_keys set jskey_lock = 0 where jskey_name = @js_keyname
	if @@rowcount = 1
	begin
		update sybmgmtdb..js_keys set jskey_id=jskey_id + 1 where jskey_name = @js_keyname
		select @err=@@error
		select @js_id=jskey_id - 1 from sybmgmtdb..js_keys where jskey_name = @js_keyname
	end
	else
	begin
		select @js_id=min(jskey_id) from sybmgmtdb..js_keys where jskey_name = @js_keyname
		set rowcount 1
		delete from sybmgmtdb..js_keys where jskey_name = @js_keyname and jskey_id=@js_id
		select @err=@@error
		set rowcount 0
	end
	if @err != 0 or @js_id is NULL or @js_id < 0 or @js_id = 2147483646
	begin
		rollback tran get_key
		commit tran get_key
		-- 19058  'Procedure %1!, jskey_name %2! unable to allocate a new id.'
		return -19058
	end
	commit tran get_key
	return @js_id
end
go
if exists (select name from sysobjects where name = 'sp_js_getkey')
begin
	print 'Created sp_js_getkey'
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_js_putkey')
	drop proc sp_js_putkey
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Releases a key value for a job scheduler table.
--
--
create proc sp_js_putkey (
        @js_keyname     varchar(64),
        @js_id          int
)
as
begin
	declare @err int
	--
	-- lookup the js_keyname
	--
	if not exists (select jskey_id from sybmgmtdb..js_keys where jskey_name = @js_keyname)
	begin
		-- 50012 'Procedure %1!, jskey_name %2! the specified keyname does not exist.'
		return -50012
	end
	--
	-- release the given id
	--
	insert into sybmgmtdb..js_keys values (@js_keyname, @js_id, 0 )
	select @err=@@error
	if @err != 0
	begin
		-- 19058  'Procedure %1!, jskey_name %2! unable to allocate a new id.'
		return -19058
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_putkey')
begin
	print 'Created sp_js_putkey'
end
go
go
if exists (select name from sysobjects where name = 'sp_js_checksched')
    drop proc sp_js_checksched
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Validates the components of a new schedule and returns the new values for any
-- components which are translated into different formats. e.g. days and dates
--
create proc sp_js_checksched (
    @caller      varchar(64),
    @sname       univarchar(64) = NULL,
    @sdesc       univarchar(128) = NULL,
    @sowner      varchar(30) = NULL,
    @sched_id    int = NULL,
    @repeats     int = 0,
    @units       varchar(8) = NULL,
    @startdate   datetime = NULL,
    @starttime   datetime = NULL,
    @enddate     datetime = NULL,
    @endtime     datetime = NULL,
    @days        int = NULL,
    @dates       int = NULL,
    @udays       varchar(128) = NULL,
    @udates      varchar(128) = NULL,
    @int_repeats int             output,
    @int_units   char(1)         output,
    @int_days    smallint        output,
    @int_dates   int             output,
    @int_udays   varchar(128)    output,
    @int_udates  varchar(128)    output
) as
begin
    declare    @err int
              , @rows int
              , @msgno int
              , @int_starttime int
              , @int_endtime int
              , @tsname univarchar(64)
              , @vcname varchar(64)

    -- If a schedule name is supplied it must not be empty, a number or 
    -- sched_<number> a name is autogenerated from 'sched_' + sched_id when a 
    -- name is not supplied.
    if @sname is not NULL
    begin
        exec @err=sp_js_check_id @name_id=@sname, @cmd=0
        if @err < 0
        begin
            select @msgno = abs(@err)
            raiserror @msgno, @caller, '@sname'
            return -@@error
        end
        if substring(@sname, 1, 6) = 'sched_'
        begin
            if patindex('%[^0-9]%', substring(@sname, 7, 
                                              char_length(@sname) - 6)) <= 0
            begin
                -- @sname is 'sched_' + a number
                -- 19091 'Procedure %1!, %2! is not a valid name.'
                select @vcname=@sname
                raiserror 19091, @caller, @vcname
                return -@@error
            end
        end

        -- Check schedule name does not already exist
        if ( @sched_id is NULL and
            exists (select sched_name 
                      from sybmgmtdb..js_schedules
                     where sched_name = @sname and sched_owner = @sowner)) 
        or ( @sched_id is not NULL and
            exists (select sched_name 
                      from sybmgmtdb..js_schedules
                     where sched_name = @sname 
                       and sched_owner = @sowner and sched_id != @sched_id))
        begin
            -- 19059 'Procedure %1!, a %2! already exists with the name %3!',
            select @vcname=@sname
            raiserror 19059, @caller, 'schedule', @vcname
            return -@@error
        end
    end

    if @repeats is NULL
        select @repeats=0
    select @int_repeats=@repeats

    if @repeats < 0
    begin
        -- 19060 'Procedure %1!, %2! must be a positive integer.'
        raiserror 19060, @caller, '@repeats'
        return -@@error
    end

    if @units is NULL or @units = ''
    begin
        if @repeats != 0
        begin
            -- 19061 'Procedure %1!, a repeating schedule must specify a value 
            -- for @units'
            raiserror 19061, @caller
            return -@@error
        end
        select @int_units=''
    end
    else
    begin
        --life is easier if we ensure units is set to a standard value
        --for each of the allowable units
        if @units = 'days' or @units = 'day' or @units = 'dd' or @units = 'd'
            select @int_units='d'
        else if @units = 'hours' or @units = 'hour' or @units = 'hh' 
             or @units = 'h'
            select @int_units='h'
        else if @units = 'minutes' or @units = 'minute' or @units = 'mm' 
             or @units = 'm'
            select @int_units='m'
        else
        begin
            -- 19062 'Procedure %1!, the parameter @units must be days, hours, 
            -- minutes, dd, mm, hh, d, h or m.'
            raiserror 19062, @caller
            return -@@error
        end
    end

    --
    -- Validate days and dates values
    --
    if ( (@udays is not NULL and @udays <> '') and
              (@udates is not NULL and @udates <> '') ) 
    or  ( @days is not NULL and @days != 0 and
              @dates is not NULL and @dates != 0 )

    begin
        -- 19063 "Procedure %1!, @days and @dates may not be used in a single 
        -- schedule."
        raiserror 19063, @caller
        return -@@error
    end

    -- Convert days and dates values to make processing simplier
    if @days is not NULL and @days != 0
    begin
        exec @err = sp_js_bits2days @days, @int_udays output
        if @err != 0
        begin
            -- 19064 'Procedure %1!, the @days parameter is incorrect. It 
            -- should be a comma separated list of days of the week.'
            raiserror 19064, @caller
            return -@@error
        end

        select @int_days=@days, @int_dates=0, @int_udates=NULL
        --print '1: days %1!, udays %2!, dates %3!, udates %4!', @int_days, 
        --@int_udays, @int_dates, @int_udates
    end
    else if @udays is not NULL and @udays <> ''
    begin
        exec @err = sp_js_days2bits @udays, @int_days output
        if @err != 0
        begin
            -- 19064 'Procedure %1!, the @days parameter is incorrect. It 
            -- should be a comma separated list of days of the week.'
            raiserror 19064, @caller
            return -@@error
        end
        exec sp_js_bits2days @int_days, @int_udays output
        select @int_dates=0, @int_udates=NULL
        --print '2: days %1!, udays %2!, dates %3!, udates %4!', @int_days, 
        --@int_udays, @int_dates, @int_udates
    end
    else if @dates is not NULL and @dates != 0
    begin
        exec @err = sp_js_bits2dates @dates, @int_udates output
        if @err != 0
        begin
            -- 19065 'Procedure %1!, the @dates parameter is incorrect. 
            --It should be a comma separated list of dates in a month.'
            raiserror 19065, @caller
            return -@@error
        end
        select @int_dates=@dates, @int_days=0, @int_udays=NULL
        --print '3: days %1!, udays %2!, dates %3!, udates %4!',
        --@int_days, @int_udays, @int_dates, @int_udates
    end
    else if @udates is not NULL and @udates <> ''
    begin
        exec @err = sp_js_dates2bits @udates, @int_dates output
        if @err != 0
        begin
            -- 19065 'Procedure %1!, the @dates parameter is incorrect. 
            --It should be a comma separated list of dates in a month.'
            raiserror 19065, @caller
            return -@@error
        end
        exec sp_js_bits2dates @int_dates, @int_udates output
        select @int_days=0, @int_udays=NULL
        --print '4: days %1!, udays %2!, dates %3!, udates %4!',
        -- @int_days, @int_udays, @int_dates, @int_udates
    end
    else    
    begin
        select @int_days=0, @int_udays=NULL, @int_dates=0, @int_udates=NULL
        --print '5: days %1!, udays %2!, dates %3!, udates %4!',
        -- @int_days, @int_udays, @int_dates, @int_udates
    end

    -- CR 350211 revise restriction to allow 1 day units but prevent days
    -- and dates, and multi day units and days or dates
    if (@int_units = 'd' and @repeats > 1)
        and ( @int_days != 0 or @int_dates != 0 )
    begin
        -- 19442 "Procedure %1!, @days and @dates restrictions are not
        -- allowed for schedules with an interval of more than one day."
        raiserror 19442, @caller
        return -@@error
    end

    if  @int_days > 0 and @int_dates > 0
    begin
        -- 19063 "Procedure %1!, @days and @dates may not be used in a 
        -- single schedule."
        raiserror 19063, @caller
        return -@@error
    end

    --
    -- We shouldn't need to validate the the dates and times as that happens
    -- when they are passed as arguments to the stored procedure.
    -- However, we should perform some logical checks, such as
    --     startdate < enddate    
    --     starttime < endtime when startdate==enddate
    -- 
    -- CR 428650-2
    -- Check for a startdate, if provided set time portion to neutral value
    --      so that is doesn't interfere with startdate/enddate comparison
    -- Create starttime and endtime values
    --
    if @startdate is NULL
    begin
        select @startdate = convert( date, getdate() )
    end
    else
    begin
        --truncating the time portion of datetime because we
        --don't use it and it can only cause problems.
        select @startdate = convert( date, @startdate )
    end


    if @starttime is not NULL
        select @int_starttime = datepart(hour,@starttime) * 60
                                + datepart(minute, @starttime)
    else
        select @int_starttime = 0

    if @endtime is not NULL
        select @int_endtime = datepart(hour,@endtime) * 60
                              + datepart(minute, @endtime)
    else
        select @int_endtime = 0

    --
    -- If enddate is supplied
    --    startdate can't be greater than enddate
    --    starttime can't be greater than endtime
    -- else
    --    above checks don't matter because there is no end to the
    --       schedule
    --
    if @enddate is not NULL
    begin
        -- CR 428650-2
        --truncating the time portion of datetime because we
        --don't use it and it can only cause problems.
        select @enddate = convert(date, @enddate )

        if( @startdate > @enddate )
        begin
            -- 19066 'Procedure %1!, the @startdate is later than
            -- the @enddate."
            raiserror 19066, @caller
            return -@@error
        end

        -- If start and end dates are equal start time must be less than
        -- or equal to end time.  
        if (@startdate = @enddate) and (@int_endtime != 0)
            and (@int_starttime > @int_endtime)
        begin
            -- 19067 'Procedure %1!, the @starttime is later than
            --        the @endtime."
            raiserror 19067, @caller
            return -@@error
        end
    end

    return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_checksched')
begin
    print 'Created sp_js_checksched'
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_js_properties')
	drop proc sp_js_properties
go
--
-- Internal JobScheduler stored procedure
--
-- Warning this procedure is not a published interface, do not use it.
--
-- Validates the properties for a scheduled job, job or schedule and
-- returns the new values for the properties as a list and a bit mask.
--
create proc sp_js_properties (
        @int_properties int,
        @type           varchar(10),
        @value          varchar(128),
        @new_properties int             output,
        @uproperties    varchar(128)    output
)
as
begin
	declare @props varchar(128)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @tmp_properties int, @i1 int, @flagbit int
--declare @props2 varchar(128)

	select @tmp_properties=@int_properties
	select @len=isnull(char_length(@value), 0), @curpos=1
--print 'value %1!, len %2!, props %3!', @value, @len, @int_properties

	if @value is NULL or @value = '0' or @value = ''
	begin
		select @new_properties=0, @uproperties=NULL
		return 0
	end
	while @curpos < @len
	begin
		--
		-- get the end of the next pair:-
		--	<prop_name>=<true|false>[,:]
		--
		select @end_pos=patindex('%[,:]%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,:
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the name=value pair
		--
		select @props=substring(@value, @curpos, @end_pos-@curpos)
--print 'curpos %1!, end_pos %2!, substring %3!', @curpos, @end_pos, @props
		--
		-- find the =,: =true or =false
		--
		select @eq_pos=patindex('%=%', @props)
		if @eq_pos <= 0				-- @property=shared,: default true
			select @eq_pos=isnull(char_length(@props), 0) + 1, @flagbit=1
		else if @eq_pos = isnull(char_length(@props), 0)	-- @property=shared=,:  error
			return -1
		else if lower (substring(@props, @eq_pos + 1, 1)) = 't'  -- =true
			select @flagbit=1
		else if lower (substring(@props, @eq_pos + 1, 1)) = 'f'  -- =false
			select @flagbit=0
		else
			return -1
		--
		-- get the property name
		--
--select @props2=substring(@props, 1, @eq_pos-1)
--print 'curpos %1!, len %2!, eq_pos %3!, str %4!', @curpos, @len, @eq_pos, @props2
		select @i1=case ltrim(rtrim(substring(@props, 1, @eq_pos-1)))
			when 'multi_task' 		then 1
			when 'run_as_owner' 		then 2
			when 'disable_on_failure' 	then 4
			when 'delete_on_completion' 	then 8
			when 'no_output_log' 		then 16
			when 'shared' 			then 32
			when 'shared_run' 		then 64
			when 'only_at_starttime'	then 128
			when 'no_job_header'		then 256
			when 'no_sql_batching'		then 512
			when 'no_conn_redirection'	then 1024
			else -1
			end
--print 'i1 %1!', @i1
		if @i1 < 0
			return -1
		if @flagbit=1
			select @tmp_properties=@tmp_properties | @i1
		else
			select @tmp_properties=@tmp_properties & ~@i1
		select @curpos=@end_pos + 1
	end
	select @props=NULL
	if @tmp_properties & 1 = 1
	begin
		if @type = 'job' or @type = 'job2'
			if @props is NULL select @props='multi_task' else select @props=@props + ':multi_task'
		else if @type != 'sjob2' return -2
		else select @tmp_properties=@tmp_properties - 1
	end
	if @tmp_properties & 2 = 2
	begin
		if @type = 'job' or @type = 'job2'
			if @props is NULL select @props='run_as_owner' else select @props=@props + ':run_as_owner'
		else if @type != 'sjob2' return -2
		else select @tmp_properties=@tmp_properties - 2
	end
	if @tmp_properties & 4 = 4
	begin
		if @type = 'sjob' or @type = 'sjob2'
			if @props is NULL select @props='disable_on_failure' else select @props=@props + ':disable_on_failure'
		else if @type != 'job2' return -2
		else select @tmp_properties=@tmp_properties - 4
	end
	if @tmp_properties & 8 = 8
	begin
		if @type = 'sjob' or @type = 'sjob2'
			if @props is NULL select @props='delete_on_completion' else select @props=@props + ':delete_on_completion'
		else if @type != 'job2' return -2
		else select @tmp_properties=@tmp_properties - 8
	end
	if @tmp_properties & 16 = 16
	begin
		if @type = 'sjob' or @type = 'sjob2'
			if @props is NULL select @props='no_output_log' else select @props=@props + ':no_output_log'
		else if @type != 'job2' return -2
		else select @tmp_properties=@tmp_properties - 16
	end
	if @tmp_properties & 32 = 32
	begin
		if @type = 'job' or @type = 'sched' or @type = 'job2'
			if @props is NULL select @props='shared' else select @props=@props + ':shared'
		else if @type != 'sjob2' return -2
		else select @tmp_properties=@tmp_properties - 32
	end
	if @tmp_properties & 64 = 64
	begin
		if @type = 'sjob' or @type = 'sjob2'
			if @props is NULL select @props='shared_run' else select @props=@props + ':shared_run'
		else if @type != 'job2' return -2
		else select @tmp_properties=@tmp_properties - 64
	end
	if @tmp_properties & 128 = 128
	begin
		if @type = 'sjob' or @type = 'sjob2'
			if @props is NULL select @props='only_at_starttime' else select @props=@props + ':only_at_starttime'
		else if @type != 'job2' return -2
		else select @tmp_properties=@tmp_properties - 128
	end
	if @tmp_properties & 256 = 256
	begin
		if @type = 'job' or @type = 'job2'
			if @props is NULL select @props='no_job_header' else select @props=@props + ':no_job_header'
		else if @type != 'sjob2' return -2
		else select @tmp_properties=@tmp_properties - 256
	end
	if @tmp_properties & 512 = 512
	begin
		if @type = 'job' or @type = 'job2'
			if @props is NULL select @props='no_sql_batching' else select @props=@props + ':no_sql_batching'
		else if @type != 'sjob2' return -2
		else select @tmp_properties=@tmp_properties - 512
	end
	if @tmp_properties & 1024 = 1024
	begin
		if @type = 'job' or @type = 'job2'
			if @props is NULL select @props='no_conn_redirection' else select @props=@props + ':no_conn_redirection'
		else if @type != 'sjob2' return -2
		else select @tmp_properties=@tmp_properties - 1024
	end
--print 'int_p %1!, value %2!, new_p %3!, uprop %4!,', @int_properties, @value, @tmp_properties, @props
	select @new_properties=@tmp_properties, @uproperties=@props
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_properties')
begin
	print 'Created sp_js_properties'
end
go
go
if exists (select name from sysobjects where name = 'sp_createjob')
	drop proc sp_createjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_createjob (  @jname       univarchar(64),
	                    @jdesc       univarchar(128) = NULL,
	                    @properties  varchar(128) = NULL,
	                    @default_timeout int = 60,
	                    @tmpl_id    int = NULL ) as
begin
	declare	@err int
                , @rows int
                , @msgno int
                , @job_id int 
	        , @len int
                , @curpos int
	        , @int_jproperties int
                , @seqno int
	        , @jproperties varchar(128)
	        , @owner char(30)
                , @tjname univarchar(64)
                , @tsname univarchar(64)
                , @created datetime
	        , @vcname varchar(64)
                , @chunk univarchar(901)
	        , @sp_name varchar(32)
	if @@trancount = 0
	    set chained off
	set transaction isolation level 1

	select  @sp_name='sp_createjob'

	-- Check job name is not NULL, empty, a number or job_<number>
	select @tjname = ltrim(rtrim(@jname))
	exec @job_id=sp_js_check_id @name_id=@tjname, @cmd=0, @table='job_'
	if @job_id < 0
	begin
	    select @msgno = abs(@job_id)
	    raiserror @msgno, @sp_name, '@jname'
	    return -@@error
	end

	-- Check job name does not already exist
	if exists (select job_name 
                   from sybmgmtdb..js_jobs 
                   where job_name = @tjname and job_owner = suser_name())
	begin
	    -- 19059 'Procedure %1!, a %2! already exists with the name %3!',
	    select @vcname=@jname
	    raiserror 19059, @sp_name, 'job', @vcname
	    return -@@error
	end

	--
	-- build the new properties for the job
	-- We ignore -2 errors as we pass in all the properties each time.
	-- err -1 -> 19088 'Procedure %1!, @properties=''%2!'', 
        -- invalid property name or value.'
	-- err -2 -> 19089 'Procedure %1!, @properties=''%2!'', 
        -- a property cannot be used with the scheduledjob, job or schedule.
	--
	exec @err=sp_js_properties 0, 'job2', @properties, 
                       @int_jproperties output, @jproperties output
	if @err = -1
	begin
	    raiserror 19088, @sp_name, @properties
	    return -@@error
	end

        -- get the current date and user name for future use
	select @created=getdate(), @owner=suser_name()

	--
	-- Generate job key (id)
	--
	exec @job_id=sp_js_getkey 'job_id'
	if @job_id < 0
	begin
	    select @msgno=abs(@job_id)
	    raiserror @msgno, @sp_name, 'job_id'
	    return -@@error
	end
	begin tran sp_createjob1

	--
	-- create the job
	--
	insert sybmgmtdb..js_jobs
		(job_id, job_type, job_properties, job_owner, job_created, 
                 job_default_timeout, job_tmpl_id, job_name, job_description, 
                 job_uproperties)
	values (@job_id, 0, @int_jproperties, @owner, @created, 
                @default_timeout, @tmpl_id, @tjname, @jdesc, 
                @jproperties)
	select @err=@@error, @rows=@@rowcount

        -- Rollback tran if insert error
	if @err != 0
	begin
	    rollback tran 
	    exec sp_js_putkey 'job_id', @job_id
	    -- 19075 'Procedure %1!, failed to insert an entry in the %2! 
            -- table, insert error %3!.'
 	    raiserror 19075, @sp_name, 'js_jobs', @err
	    return -@@error
	end

	commit tran
	return @job_id
end
go
if exists (select name from sysobjects where name = 'sp_createjob')
begin
	print 'Created sp_createjob'
	grant execute on sp_createjob to js_user_role
	grant execute on sp_createjob to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_createschedule')
	drop proc sp_createschedule
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
-- 
create proc sp_createschedule (
	@sname		univarchar(64)	= NULL,
	@sdesc		univarchar(128)	= NULL,
	@sproperties	varchar(128)	= NULL,

	@repeats	int		= 0,
	@units		varchar(8)	= NULL,
	@startdate	varchar(64)	= NULL,
	@starttime	varchar(64)	= NULL,
	@enddate	varchar(64)	= NULL,
	@endtime	varchar(64)	= NULL,

	@days		int		= NULL,
	@dates		int		= NULL,
	@udays		varchar(128)	= NULL,
	@udates		varchar(128)	= NULL
)
as
begin
	declare	@err int, @rows int, @msgno int, @sched_id int
	declare @owner char(30), @int_units char(1), @tsname univarchar(64), @created datetime
	declare @int_repeats int, @int_days smallint, @int_dates int, @int_properties int
	declare @cur_startdate datetime, @cur_starttime datetime, @cur_enddate datetime, @cur_endtime datetime
	declare @int_udays varchar(128), @int_udates varchar(128)
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_createschedule'

	select @tsname=ltrim(rtrim(@sname))
	if @tsname is NULL
	begin
		raiserror 19048, @sp_name, '@sname'
		return -@@error
	end
	set arithabort off	-- restored on return
	if @startdate is not NULL
	begin
		if @startdate = '' select @startdate=NULL
		select @cur_startdate=convert(datetime, @startdate)
		if @@error != 0
		begin
			-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
			raiserror 19070, @sp_name, '@startdate', @startdate
			return -@@error
		end
	end
	if @starttime is not NULL
	begin
		if @starttime = '' select @starttime=NULL
		select @cur_starttime=convert(datetime, @starttime)
		if @@error != 0
		begin
			-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
			raiserror 19070, @sp_name, '@starttime', @starttime
			return -@@error
		end
	end
	if @enddate is not NULL
	begin
		if @enddate = '' select @enddate=NULL
		select @cur_enddate=convert(datetime, @enddate)
		if @@error != 0
		begin
			-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
			raiserror 19070, @sp_name, '@enddate', @enddate
			return -@@error
		end
	end
	if @endtime is not NULL
	begin
		if @endtime = '' select @endtime=NULL
		select @cur_endtime=convert(datetime, @endtime)
		if @@error != 0
		begin
			-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
			raiserror 19070, @sp_name, '@endtime', @endtime
			return -@@error
		end
	end
	set arithabort on
	select @created=getdate(), @owner=suser_name()

	exec @err=sp_js_checksched @caller=@sp_name, @sname=@tsname, 
                        @sdesc=@sdesc, @sowner=@owner, @sched_id=NULL,
			@repeats=@repeats, @units=@units,
			@startdate=@cur_startdate, @starttime=@cur_starttime,
			@enddate=@cur_enddate, @endtime=@cur_endtime,
			@days=@days, @dates=@dates, @udays=@udays, 
                        @udates=@udates, @int_repeats=@int_repeats output, 
                        @int_units=@int_units output, @int_days=@int_days output,                        @int_dates=@int_dates output,
			@int_udays=@int_udays output, 
                        @int_udates=@int_udates output
	if @err < 0
		return @err	-- sp_js_checksched raises the error

	if @sproperties = 'shared=true'	
                select @sproperties='shared'
	else if @sproperties = 'shared=false'	
                select @sproperties=''

	if @sproperties is not NULL and @sproperties != '' and 
           @sproperties != 'shared'
	begin
		--19088 'Procedure %1!, @sproperties=''%2!'', invalid property name or value.'
		raiserror 19088, @sp_name, @sproperties
		return -@@error
	end
	if @sproperties = 'shared'
		select @int_properties=32
	else	select @int_properties=0

	--
	-- Generate next schedule id
	--
	exec @sched_id=sp_js_getkey 'sched_id'
	if @sched_id < 0
	begin
		select @msgno=abs(@sched_id)
		raiserror @msgno, @sp_name, 'sched_id'
		return -@@error
	end
	if @tsname is NULL or @tsname = ''
		select @tsname='sched_' + convert(varchar(32), @sched_id)
	--
	-- Create schedule
	--
	begin tran sp_createschedule
	save tran nested_tran
	insert sybmgmtdb..js_schedules
		(sched_id, sched_type, sched_properties, sched_name, 
                 sched_description, sched_owner, sched_created, sched_interval, 
                 sched_interval_units, sched_startdate, sched_starttime, 
                 sched_enddate, sched_endtime, sched_days, sched_dates, 
                 sched_uproperties, sched_uinterval, sched_udays, sched_udates, 
                 sched_expired)
	values (@sched_id, 0, @int_properties, @tsname, @sdesc, @owner, @created,
                @int_repeats, @int_units, @cur_startdate, @cur_starttime, 
                @cur_enddate, @cur_endtime, @int_days, @int_dates, @sproperties,
                convert(varchar(32), @int_repeats) + @units, @int_udays, 
                @int_udates, 0)

	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		exec sp_js_putkey 'sched_id', @sched_id
		-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
		raiserror 19075, @sp_name, 'js_schedules', @err
		return -@@error
	end
	commit tran
	return @sched_id
end
go
if exists (select name from sysobjects where name = 'sp_createschedule')
begin
	print 'Created sp_createschedule'
	grant execute on sp_createschedule to js_user_role
	grant execute on sp_createschedule to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_createscheduledjob')
	drop proc sp_createscheduledjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
-- NOTE:  This procedure replaces the createscheduledjob procedure for 
-- 15.0 releases.
-- This procedures can be used to create a scheduled job using an existing
-- job and existing schedule.  This method is used by the ASEP JS GUI to
-- create a scheduled job from the Scheduled Job Wizard.
--
-- @jobid        create a new job if NULL
-- @schedid      create a new schedule if NULL
-- @sjname       scheduled job name
-- @sjproperties scheduled job properties
-- @server       scheduled job server
-- @timeout      scheduled job timeout
-- @jname        job name
-- @sname        schedule name
--
create proc sp_createscheduledjob ( @jobid int = NULL,       
	                          @schedid int = NULL,      
	                          @sjname univarchar(64)=NULL, 
	                          @sjproperties  varchar(128) = NULL, 
	                          @server varchar(30),          
	                          @timeout int = 60,            
	                          @jname univarchar(64)=NULL, 
	                          @sname univarchar(64)  = NULL ) as
begin
    declare   @err int
            , @rows int
            , @msgno int
            , @job_id int  
            , @sched_id int  
            , @sjob_id int
            , @int_sjproperties int
            , @seqno int
            , @sjprops varchar(128)
            , @owner char(30)
            , @tsjname univarchar(64)
            , @tjname univarchar(64)
            , @tsname univarchar(64)
            , @created datetime
            , @sp_name varchar(32)
            , @tmp_name varchar(32)

    -- We create just the scheduled job row if the user provides IDs
    -- for the job and the schedule.
    -- This would be the case when a job is scheduled from the context menu
    -- Else we create a new job and a new schedule, as from the Add Scheduled
    -- job object.

    if( @@trancount = 0 )
        set chained off

    set transaction isolation level 1
    select  @sp_name='sp_createscheduledjob'

    -- Set the created date to now, set owner to current user
    select @created=getdate(), @owner=suser_name(), @sched_id=@schedid
 
    -- If user didn't supply the jobid, we need to verify the job name.
    if( @jobid is NULL )
    begin
        select @tjname = ltrim(rtrim(@jname))

        -- Check job name is not NULL, empty, a number or job_<number>
        exec @job_id=sp_js_check_id @name_id=@tjname, @cmd=0, @table='job',
             @return_id=1
        if( @job_id < 0 )
        begin
            select @msgno = abs(@job_id)
            raiserror @msgno, @sp_name, '@jname'
            return -@@error
        end
        --select @tmp_name = @jname
        --print 'job_id for %1! is %2!', @tmp_name, @job_id
      end
    else
    begin
        -- Check job id represents a valid job id
        select @jname = convert(varchar(32),@jobid)
        exec @job_id=sp_js_check_id @name_id=@jname, @cmd=1, @table='job'
        if( @job_id < 0 )
        begin
            select @msgno = abs(@job_id)
            raiserror @msgno, @sp_name, '@jname'
            return -@@error
        end
        --print 'job_id is %1!', @job_id
    end
    
    -- If user didn't supply the schedid, we need to verify the sched name.
    if( @schedid is NULL )
    begin
        select @tsname = ltrim(rtrim(@sname))
        -- Check sched name is not NULL, empty, a number or sched_<number>
        exec @sched_id=sp_js_check_id @name_id=@tsname, @cmd=0, @table='sched',
             @return_id=1
        if( @sched_id < 0 )
        begin
            select @msgno = abs(@sched_id)
            raiserror @msgno, @sp_name, '@sname'
            return -@@error
        end
        --select @tmp_name = @sname
        --print 'sched_id for %1! is %2!', @tmp_name, @sched_id
    end
    else
    begin
        -- Check sched id represents a valid sched id
        select @sname = convert(varchar(32),@schedid)
        exec @sched_id=sp_js_check_id @name_id=@sname, @cmd=1, @table='sched'
        if( @sched_id < 0 )
        begin
            select @msgno = abs(@sched_id)
            raiserror @msgno, @sp_name, '@sname'
            return -@@error
        end
        --print 'sched_id is %1!', @sched_id
    end

    -- we use @sched_id from now on
    --
    -- build the new properties for the scheduled job
    -- We ignore -2 errors as we pass in all the properties each time.
    -- err -1 -> 19088 'Procedure %1!, @properties=''%2!'', 
    --                 invalid property name or value.'
    -- err -2 -> 19089 'Procedure %1!, @properties=''%2!'', 
    --                 a property cannot be used with the scheduledjob 
    --
    --convert the sched job props to a bitmap
    exec @err=sp_js_properties 0, 'sjob2', @sjproperties, 
                               @int_sjproperties output, @sjprops output
    if( @err = -1 )
    begin
        raiserror 19088, @sp_name, @sjproperties
        return -@@error
    end

    -- Start a transaction
    begin tran 

    --
    -- create the scheduled job
    --
    -- Get the schedjob key
    exec @sjob_id=sp_js_getkey 'sjob_id'
    if( @sjob_id < 0 )
    begin
        select @msgno=abs(@sjob_id)
        raiserror @msgno, @sp_name, 'sjob_id'
        return -@@error
    end
    --print 'sjob_id is %1!', @sjob_id
    select @tsjname = ltrim(rtrim(@sjname))
    if( @tsjname = NULL )
        select @tsjname='sjob_' + convert(varchar(32), @sjob_id)

    --print 'sjob_id = %1!, sjob_job_id = %2!, sjob_sched_id = %3!', @sjob_id, @job_id, @sched_id
    insert sybmgmtdb..js_scheduledjobs (sjob_id, sjob_job_id, sjob_sched_id, 
                                        sjob_enable, sjob_properties, 
                                        sjob_owner, sjob_created, sjob_server, 
                                        sjob_timeout_value, sjob_name, 
                                        sjob_uproperties)
                                values (@sjob_id, @job_id, @sched_id,
                                        1, @int_sjproperties, 
                                        @owner, @created, @server, 
                                        @timeout, @tsjname, 
                                        @sjprops)

    select @err=@@error, @rows=@@rowcount

    -- handle the error
    if( @err != 0 )
    begin
        rollback tran
        exec sp_js_putkey 'sjob_id',  @sjob_id

        -- 19075 'Procedure %1!, failed to insert an entry in the %2! table, 
        -- insert error %3!.'
        raiserror 19075, @sp_name, 'js_scheduledjobs', @err
        return -@@error
    end
    commit tran

    --
    -- inform the ASE task
    --
    exec sp_js_wakeup 'job_created', @sjob_id
    return @sjob_id
end
go
if exists (select name from sysobjects where name = 'sp_createscheduledjob')
begin
    print 'Created sp_createscheduledjob'
    grant execute on sp_createscheduledjob to js_user_role
    grant execute on sp_createscheduledjob to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_bindscheduledjob')
	drop proc sp_bindscheduledjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_bindscheduledjob (
	@jname_id	univarchar(64),
	@sname_id	univarchar(64)
)
as
begin
	declare @sp_name varchar(32)
	declare @err int, @rows int, @msgno int, @job_id int, @sched_id int, @sjob_id int, @is_admin int
	declare @owner char(30), @created datetime, @tjname univarchar(64), @tsname univarchar(64)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_bindscheduledjob'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the lookup the jname_id and sname_id, as a name or as an id
	--
	select @tjname = rtrim(@jname_id)
	select @tjname = ltrim(@tjname)
	exec @job_id=sp_js_check_id @name_id=@tjname, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
	if @job_id < 0
	begin
		select @msgno = abs(@job_id)
		raiserror @msgno, @sp_name, '@jname_id'
		return -@@error
	end

	select @tsname = rtrim(@sname_id)
	select @tsname = ltrim(@tsname)
	exec @sched_id=sp_js_check_id @name_id=@tsname, @cmd=2, @table='sched', @return_id=1, @is_admin=@is_admin
	if @sched_id < 0
	begin
		select @msgno = abs(@sched_id)
		raiserror @msgno, @sp_name, '@sname_id'
		return -@@error
	end
	--
	-- When the caller has js_admin_role, but is not the job/schedule owner and the job/schedule are not shared
	-- we allow a new scheduled job to be created. This allows js_admin_role to grant access to individual
	-- individual users, a shared job would allow access by any js_user_role 
	--
	--
	-- We do not prevent multiple instances of the same job_id and sched_id
	-- being bound as different scheduled jobs
	--
	select @created=getdate(), @owner=suser_name()
	--
	-- Generate the next js_scheduledjobs id
	--
	exec @sjob_id=sp_js_getkey 'sjob_id'
	if @sjob_id < 0
	begin
		select @msgno=abs(@sjob_id)
		raiserror @msgno, @sp_name, 'sjob_id'
		return -@@error
	end
	begin tran sp_bindscheduledjob
	save tran nested_tran
	--
	-- update lock the schedule
	--
	update sybmgmtdb..js_schedules set sched_update=@@spid where sched_id = @sched_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_schedules', @err
		return -@@error
	end
	--
	-- update lock the job
	--
	update sybmgmtdb..js_jobs set job_update=@@spid where job_id = @job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_jobs', @err
		return -@@error
	end
	--
	-- create the scheduled job
	--
	select @tjname='sjob_' + convert(varchar(32), @sjob_id)

	insert sybmgmtdb..js_scheduledjobs
		(sjob_id, sjob_job_id, sjob_sched_id, sjob_enable, sjob_properties,
			sjob_owner, sjob_created, sjob_server, sjob_name, sjob_uproperties)
	values (@sjob_id, @job_id, @sched_id, 1, 0, @owner, @created, NULL, @tjname, NULL)
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		exec sp_js_putkey 'sjob_id', @sjob_id
		-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
		raiserror 19075, @sp_name, 'js_scheduledjobs', @err
		return -@@error
	end
	--
	-- release the job
	--
	update sybmgmtdb..js_jobs set job_update=0 where job_id = @job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_jobs', @err
		return -@@error
	end
	--
	-- release the schedule
	--
	update sybmgmtdb..js_schedules set sched_update=0 where sched_id = @sched_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_schedules', @err
		return -@@error
	end
	commit tran
	--
	-- tell the ASE task
	--
	exec sp_js_wakeup 'job_created', @sjob_id
	return @sjob_id
end
go
if exists (select name from sysobjects where name = 'sp_bindscheduledjob')
begin
	print 'Created sp_bindscheduledjob'
	grant execute on sp_bindscheduledjob to js_user_role
	grant execute on sp_bindscheduledjob to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_unbindscheduledjob')
	drop proc sp_unbindscheduledjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
-- 
create proc sp_unbindscheduledjob (
	@sjname_id		univarchar(64)
)
as
begin
	declare @sp_name varchar(32)
	declare @err int, @rows int, @msgno int, @job_id int, @sched_id int, @sjob_id int
	declare @tjname univarchar(64), @is_admin int, @vcname varchar(64)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_unbindscheduledjob'
	select  @is_admin=proc_role('js_admin_role')

	-- Check job name for NULL or empty
	select @tjname = rtrim(@sjname_id)
	select @tjname = ltrim(@tjname)
	--
	-- sjname_id is a name or an id which must exist in the scheduledjobs table.
	--
	exec @sjob_id=sp_js_check_id @name_id=@tjname, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
	if @sjob_id < 0
	begin
		select @msgno = abs(@sjob_id)
		raiserror @msgno, @sp_name, '@sjname_id'
		return -@@error
	end
	--
	-- This might be a shared scheduledjob, must be js_admin_role or own it
	--
	select @err=sjob_id from sybmgmtdb..js_scheduledjobs where sjob_id=@sjob_id and
		(@is_admin = 1 or sjob_owner=suser_name())
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_scheduledjobs', @err
		return -@@error
	end
	if @rows <= 0
	begin
		-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
		raiserror 19084, @sp_name 
		return -@@error
	end
	--
	-- and there is only one
	--
	if @rows > 1 
	begin
		-- 19071 'procedure %1!, parameter %2!, more than one scheduled job exists with that name.'
		raiserror 19071, @sp_name, '@sjname_id'
		return -@@error
	end
	--
	-- make sure it's not running
	--
	if exists (select jsh_sjobid from sybmgmtdb..js_history
		where jsh_sjobid = @sjob_id and (jsh_state like '[QR]%' or jsh_state like '[CTX]1') )
	begin
		-- 19072 'Procedure %1!, unable to perform the operation while running jobs are using %2!.'
		select @vcname=@sjname_id
		raiserror 19072, @sp_name, @vcname
		return -@@error
	end
	--
	-- delete the scheduled job
	--
	begin tran sp_unbindscheduledjob
	save tran nested_tran
	delete from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19073 'Procedure %1, failed to delete a job entry from the js_scheduledjobs table.'
		raiserror 19073, @sp_name, 'js_scheduledjobs', @err
		return -@@error
	end
	--
	-- did it start between our first check and the delete ?
	--
	if exists (select jsh_sjobid from sybmgmtdb..js_history
		where jsh_sjobid = @sjob_id and (jsh_state like '[QR]%' or jsh_state like '[CTX]1') )
	begin
		rollback tran nested_tran
		commit tran
		-- 19072 'Procedure %1!, unable to perform the operation while running jobs are using %2!.'
		select @vcname=@sjname_id
		raiserror 19072, @sp_name, @vcname
		return -@@error
	end
	commit tran
	--
	-- inform the ASE task
	exec sp_js_wakeup 'job_deleted', @sjob_id
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_unbindscheduledjob')
begin
	print 'Created sp_unbindscheduledjob'
	grant execute on sp_unbindscheduledjob to js_user_role
	grant execute on sp_unbindscheduledjob to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_addjobtext')
	drop proc sp_addjobtext
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_addjobtext (
	@jname_id	univarchar(64),
	@text		univarchar(8000)	= NULL
)
as
begin
	declare @sp_name varchar(32)
	declare @err int, @rows int, @msgno int, @job_id int, @seqno int, @curpos int, @len int
	declare @tjname univarchar(64), @chunk univarchar(901), @is_admin int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_addjobtext'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the lookup the jname_id, as a name or as an id
	--
	select @tjname = ltrim(rtrim(@jname_id))
	exec @job_id=sp_js_check_id @name_id=@tjname, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
	if @job_id < 0
	begin
		select @msgno = abs(@job_id)
		raiserror @msgno, @sp_name, '@jname_id'
		return -@@error
	end
	begin tran sp_addjobtext
	save tran nested_tran
	--
	-- update lock the job
	--
	update sybmgmtdb..js_jobs set job_update=@@spid where job_id = @job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_jobs', @err
		return -@@error
	end
	--
	-- Must own the job, callers with js_admin_role are not allowed to
	-- modify the text of jobs they do not own.
	--
	if not exists (select job_id from sybmgmtdb..js_jobs where job_id=@job_id and job_owner=suser_name())
	begin
		rollback tran nested_tran
		commit tran
		-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
		raiserror 19084, @sp_name 
		return -@@error
	end
	select @seqno=max(jcmd_seqno) from sybmgmtdb..js_commands where jcmd_job_id = @job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
		raiserror 19075, @sp_name, 'js_commands', @err
		return -@@error
	end
	if @seqno is NULL
		select @seqno=0
	else
		select @seqno=@seqno+1
	select @curpos=1, @len=isnull(char_length(@text), 0)
	if @len > 0
	begin
		select	@text = ' ' + @text + ' '
	end
	while @curpos <= @len
	begin
		select @chunk=substring(@text, @curpos, 900) + char(10)
		insert sybmgmtdb..js_commands (jcmd_job_id, jcmd_type, jcmd_seqno, jcmd_text)
			values (@job_id, 0, @seqno, @chunk)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_commands', @err
			return -@@error
		end
		select @seqno=@seqno+1, @curpos=@curpos + 900
	end
	--
	-- release the update lock
	--
	update sybmgmtdb..js_jobs set job_update=0 where job_id = @job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_jobs', @err
		return -@@error
	end
	commit tran
	return 0
end
go
--
--
if exists (select name from sysobjects where name = 'sp_addjobtext')
begin
	print 'Created sp_addjobtext'
	grant execute on sp_addjobtext to js_user_role
	grant execute on sp_addjobtext to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_dropjobtext')
	drop proc sp_dropjobtext
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_dropjobtext (
	@jname_id		univarchar(64)
)
as
begin
	declare @sp_name varchar(32)
	declare @err int, @rows int, @msgno int, @job_id int, @is_admin int
	declare @tjname univarchar(64)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_dropjobtext'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the lookup the jname_id, as a name or as an id
	--
	select @tjname = rtrim(@jname_id)
	select @tjname = ltrim(@tjname)
	exec @job_id=sp_js_check_id @name_id=@tjname, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
	if @job_id < 0
	begin
		select @msgno = abs(@job_id)
		raiserror @msgno, @sp_name, '@jname_id'
		return -@@error
	end
	--
	-- Must own the job, callers with js_admin_role are not allowed to
	-- modify the text of jobs they do not own.
	--
	if not exists (select job_id from sybmgmtdb..js_jobs where job_id=@job_id and job_owner=suser_name())
	begin
		-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
		raiserror 19084, @sp_name 
		return -@@error
	end

	delete from sybmgmtdb..js_commands where jcmd_job_id = @job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
		raiserror 19073, @sp_name, 'js_commands', @err
		return -@@error
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_dropjobtext')
begin
	print 'Created sp_dropjobtext'
	grant execute on sp_dropjobtext to js_user_role
	grant execute on sp_dropjobtext to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_sjobmodify')
	drop proc sp_sjobmodify
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobmodify  @name univarchar(),  @option univarchar()
--
--      @name is the name or id of a scheduled job, a job or a schedule to
--      be updated.
--      The selection is made by using a prefix of sjname=, jname= or sname=.
--      With no prefix the default is the name or id of a scheduled job.
--      Example:-
--              'sjname=scheduled_job_name_or_id'
--              'jname=job_name_or_id'
--              'sname=schedule_name_or_id'
--
--      @option is a list of name=value pairs for the fields to update.
--
create proc sp_sjobmodify (
	@name		univarchar(128),
	@option		univarchar(4000) = NULL
)
as
begin
	declare @opt_val_pair univarchar(512), @opt_name univarchar(512), @opt_value univarchar(512)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @sp_name varchar(32), @name_value univarchar(64), @tell_ase int, @chunk univarchar(901)
	declare @err int, @rows int, @msgno int, @is_admin int
	declare @sjob_id int, @job_id int, @sched_id int, @sj_opt int, @j_opt int, @s_opt int, @id int
	declare @new_properties int, @int_properties int, @cur_uproperties varchar(128), @seqno int
	--
	-- current scheduled job values
	--
	declare @cur_sjname univarchar(64), @cur_enable int, @cur_sjowner varchar(30)
	declare @cur_server varchar(30), @cur_timeout int, @cur_locale varchar(30)
	-- current job values
	declare @cur_jname univarchar(64), @cur_jdesc univarchar(128), @cur_jcmd varchar(512)
	declare @cur_jowner varchar(30), @cur_default_timeout int, @cur_tmpl_id int, @prev_jowner varchar(30)
	-- current schedule values
	declare @cur_sname univarchar(64), @cur_sdesc univarchar(128), @cur_sowner varchar(30)
	declare @cur_repeats int, @cur_units char(1), @cur_startdate datetime, @cur_starttime datetime
	declare @cur_enddate datetime, @cur_endtime datetime, @cur_days smallint, @cur_dates int
	declare @cur_udays varchar(128), @cur_udates varchar(128), @cur_urepeats varchar(32), @cur_expired int
	declare @int_repeats int, @int_units char(1), @int_days int, @int_dates int
	declare @int_udays varchar(128), @int_udates varchar(128)
	--
	-- new scheduled job values
	--
	declare @sjname univarchar(64), @enable int, @properties varchar(128), @sjowner varchar(30)
	declare @server varchar(30), @timeout int, @locale varchar(30)
	-- new job values
	declare @jname univarchar(64), @jdesc univarchar(128), @jcmd varchar(1801), @jproperties varchar(128)
	declare @jowner varchar(30), @default_timeout int, @tmpl_id int
	-- new schedule values
	declare @sname univarchar(64), @sdesc univarchar(128), @sproperties varchar(128), @sowner varchar(30)
	declare @reset varchar(8), @repeats varchar(32), @startdate varchar(64), @starttime varchar(64)
	declare @enddate varchar(64), @endtime varchar(64), @days varchar(128), @dates varchar(128)
	-- 
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobmodify'
	select  @tell_ase=0, @sj_opt=0, @j_opt=0, @s_opt=0
	select @is_admin=proc_role('js_admin_role')
	--
	-- Get and validate the name or id of the scheduled job, job or schedule.
	--
	select @opt_val_pair = ltrim(rtrim(@name))
	select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)
	if @eq_pos <= 0				-- no prefix, defaults to scheduled job
		select @opt_name='sjname', @opt_value=@opt_val_pair
	else if @eq_pos = @opt_val_len		-- opt_name=  error
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	else
	begin
		select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
		select @opt_name=ltrim(rtrim(@opt_name))
		select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
		select @opt_value = ltrim(rtrim(@opt_value))
	end
	--
	-- Can modify a scheduled job, a job or a schedule
	--
	select @sjob_id=NULL, @job_id=NULL, @sched_id=NULL
	if @opt_name = 'sjname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
		if @id < 0
		begin
			select @msgno = abs(@id)
			raiserror @msgno, @sp_name, '@name'
			return -@@error
		end
		select @sjob_id=@id
		select @job_id=sjob_job_id, @sched_id=sjob_sched_id from sybmgmtdb..js_scheduledjobs
			where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		if @rows <= 0
		begin
			-- 19052 "Procedure %1!, parameter %2!, the specified scheduled job does not exist."
                	select @vcname=@name
			raiserror 19052, @sp_name, @vcname
			return -@@error
		end
	end
	else if @opt_name = 'jname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
		select @job_id=@id
	end
	else if @opt_name = 'sname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sched', @return_id=1, @is_admin=@is_admin
		select @sched_id=@id
	end
	else
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
		select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	if @id < 0
	begin
		select @msgno = abs(@id)
		raiserror @msgno, @sp_name, '@name'
		return -@@error
	end
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @option=ltrim(rtrim(@option))
	select @len=isnull(char_length(@option), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @option)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @option=stuff(@option, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @option=stuff(@option, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@option, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=,  error
		begin
			-- for modify we want to treat this as reseting the option
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))
			select @opt_value=' '
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	--select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			--raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			--return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		--
		-- scheduled job options
		--	sjname, enable, properties, owner, server, timeout, locale
		-- job options
		--	jname, jdesc, jcmd, jproperties, jowner, default_timeout, tmpl_id
		-- schedule schedule
		--	sname, sdesc, sowner, sproperties, reset, repeats,
		--	startdate, starttime, enddate, endtime, days, dates
		--
		if      @opt_name = 'sjname'	select @sjname=@opt_value, @sj_opt=1
		else if @opt_name = 'server'	select @server=@opt_value, @sj_opt=1
		else if @opt_name = 'locale'	select @locale=@opt_value, @sj_opt=1
		else if @opt_name = 'jname'	select @jname=@opt_value,  @j_opt=1
		else if @opt_name = 'jdesc'	select @jdesc=@opt_value,  @j_opt=1
		else if @opt_name = 'sname'	select @sname=@opt_value,  @s_opt=1
		else if @opt_name = 'sdesc'	select @sdesc=@opt_value,  @s_opt=1
		else if @opt_name = 'reset'	select @reset='true', @s_opt=1
		else if @opt_name = 'startdate'	select @startdate=@opt_value, @s_opt=1
		else if @opt_name = 'starttime'	select @starttime=@opt_value, @s_opt=1
		else if @opt_name = 'enddate'	select @enddate=@opt_value, @s_opt=1
		else if @opt_name = 'endtime'	select @endtime=@opt_value, @s_opt=1
		else if @opt_name = 'days'	select @days=@opt_value,  @s_opt=1
		else if @opt_name = 'dates'	select @dates=@opt_value, @s_opt=1
		else if @opt_name = 'repeats'
		begin
			select @repeats=@opt_value, @s_opt=1
			if @repeats is NULL or @repeats = ' ' or @repeats = '0'
				select @int_repeats=0, @int_units=' '
			else
			begin
				select @pos=patindex('%[^-0-9]%', @repeats)
				if @pos is NULL or @pos < 1
				begin
					select @int_units='m'
				end
				else
				begin
					select @opt_val_pair=substring(@opt_value, @pos, isnull(char_length(@repeats), 0) - @pos + 1)
					select @int_units=case @opt_val_pair
					when 'days'    then 'd' when 'day'    then 'd' when 'dd' then 'd' when 'd' then 'd'
					when 'hours'   then 'h' when 'hour'   then 'h' when 'hh' then 'h' when 'h' then 'h'
					when 'minutes' then 'm' when 'minute' then 'm' when 'mm' then 'm' when 'm' then 'm'
					else '-'
					end
					if @int_units = '-'
					begin
						-- 19062 'Procedure %1!, units must be days, hours, minutes, dd, mm, hh, d, h or m.'
						raiserror 19062, @sp_name
						return -@@error
					end
					select @opt_val_pair=substring(@repeats, 1, @pos - 1)
					exec @int_repeats=sp_js_check_id @name_id=@opt_val_pair, @cmd=3
				end
				if @int_repeats = 0
				begin
					select @int_units=' '
				end
			end
			if @int_repeats < 0
			begin
				-- 19060 'Procedure %1!, %2! must be a positive integer.'
				raiserror 19060, @sp_name, 'repeats'
				return -@@error
			end
		end
		else if @opt_name = 'jcmd'
		begin
			-- opt_val_pair is only 512, so re-select into @jcmd
			select @jcmd=substring(@option, @curpos, @end_pos-@curpos)
			select @eq_pos=patindex('%=%', @jcmd)
			select @jcmd=substring(@jcmd, @eq_pos + 1, @end_pos-@curpos), @j_opt=1
		end
		else if @opt_name = 'enable'
		begin
			if @opt_value = 'true' or @opt_value = '1'	 select @enable=1, @sj_opt=1
			else if @opt_value = 'false' or @opt_value = '0' select @enable=0, @sj_opt=1
			else
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
                		select @vcbuf1=@opt_name, @vcbuf2=@opt_value
				raiserror 19070, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @opt_name = 'properties' or @opt_name = 'jproperties' or @opt_name = 'sproperties'
				or @opt_name = 'sjproperties'
		begin
			-- syntax check the properties string, updates done later.
			if @opt_name = 'properties' or @opt_name = 'sjproperties'
				exec @err=sp_js_properties 0, 'sjob', @opt_value, @int_properties output, @cur_uproperties output
			else if @opt_name = 'jproperties'
				exec @err=sp_js_properties 0, 'job', @opt_value, @int_properties output, @cur_uproperties output
			else	exec @err=sp_js_properties 0, 'sched', @opt_value, @int_properties output, @cur_uproperties output

			if @err < 0
			begin
				-- -1 19088 'Procedure %1!, @properties=''%2!'', invalid property name or value.'
				-- -2 19089 'Procedure %1!, @properties=''%2!'', a property cannot be used with the scheduledjob, job or schedule.
                		select @vcbuf1=@opt_value
				if @err = -1
					raiserror 19088, @sp_name, @vcbuf1
				else	raiserror 19089, @sp_name, @vcbuf1
				return -@@error
			end
			if      @opt_name = 'properties'	select @properties=@opt_value, @sj_opt=1
			else if @opt_name = 'sjproperties'	select @properties=@opt_value, @sj_opt=1
			else if @opt_name = 'jproperties'	select @jproperties=@opt_value, @j_opt=1
			else					select @sproperties=@opt_value, @s_opt=1
		end
		else if @opt_name = 'owner' or @opt_name = 'jowner' or @opt_name = 'sowner' or @opt_name = 'sjowner'
		begin
			if @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			--
			-- Validate server username
			--
			if suser_id(@opt_value) is NULL
			begin
				-- 19080 'Procedure %1!, %2! is not a valid server username.'
                		select @vcbuf1=@opt_value
				raiserror 19080, @sp_name, @vcbuf1
				return -@@error
			end
			if      @opt_name = 'owner'  or @opt_name = 'sjowner' select @sjowner=@opt_value, @sj_opt=1
			else if @opt_name = 'jowner' select @jowner=@opt_value, @j_opt=1
			else			     select @sowner=@opt_value, @s_opt=1
		end
		else if @opt_name = 'timeout' or @opt_name = 'default_timeout' or @opt_name = 'tmpl_id'
		begin
			if @opt_value=' ' select @opt_value='0'
			-- check that the value is a +ve integer
			exec @err=sp_js_check_id @name_id=@opt_value, @cmd=3
			if @err < 0
			begin
				-- 19060 'Procedure %1!, %2! must be a positive integer.'
				-- raiserror 19060, @sp_name, @opt_name
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
                		select @vcbuf1=@opt_name, @vcbuf2=@opt_value
				raiserror 19070, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			if      @opt_name = 'timeout'		select @timeout=@err, @sj_opt=1
			else if @opt_name = 'default_timeout'	select @default_timeout=@err, @j_opt=1
			else					select @tmpl_id=@err, @j_opt=1
		end
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
			select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end

		select @curpos=@end_pos + 1
	end
	
	-- If @name is a job or schedule, only allow job or schedule fields to be modified
	if @sjob_id is NULL
	begin
		-- 19092 'Procedure %1!, the name or id of a scheduled job or a job is needed when options for jobs are supplied.'
		-- 19093 'Procedure %1!, the name or id of a scheduled job or a schedule is needed when options for schedules are supplied.'
		-- 19094 'Procedure %1!, the name or id of a scheduled job is needed when options for schedulejobs are supplied.'
		if      @sj_opt = 1			select @msgno=19094
		else if @job_id   is NULL and @j_opt = 1	select @msgno=19092
		else if @sched_id is NULL and @s_opt = 1	select @msgno=19093
		else select @msgno=0
		if @msgno != 0
		begin
			raiserror @msgno, @sp_name
			return -@@error
		end
	end
	else
	begin
		-- clear the id's if we are not changing any of the fields.
		if @sj_opt = 0	select @sjob_id  = NULL
		if @j_opt  = 0	select @job_id   = NULL
		if @s_opt  = 0	select @sched_id = NULL
	end
	--
	-- Validate the name for a job
	--
	if @jname is not NULL
	begin
		exec @err=sp_js_check_id @name_id=@jname, @cmd=0, @table='job_'
		if @err < 0
		begin
			select @msgno = abs(@err)
			raiserror @msgno, @sp_name, 'jname'
			return -@@error
		end
	end
	-- Validate the name for a schedule
	if @sname is not NULL
	begin
		exec @err=sp_js_check_id @name_id=@sname, @cmd=0, @table='sched_'
		if @err < 0
		begin
			select @msgno = abs(@err)
			raiserror @msgno, @sp_name, 'sname'
			return -@@error
		end
	end
	if @sjname is not NULL
	begin
		exec @err=sp_js_check_id @name_id=@sjname, @cmd=0, @table='sjob_'
		if @err < 0
		begin
			select @msgno = abs(@err)
			raiserror @msgno, @sp_name, 'sjname'
			return -@@error
		end
	end
	--
	-- begin tran
	-- update lock the schedule, job, then scheduled job
	-- read the current values
	-- perform any additional validation
	-- update the job, schedule, scheduled job - the order does 
	--	not matter once they have been locked.
	-- commit, release the locks
	-- tell ASE task
	--
	begin tran sp_sjobmodify
	save  tran nested_tran
	if @sched_id is not NULL
	begin
		update sybmgmtdb..js_schedules set sched_update=@@spid where sched_id=@sched_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_schedules', @err
			return -@@error
		end
	end
	if @job_id is not NULL
	begin
		update sybmgmtdb..js_jobs set job_update=@@spid where job_id=@job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
		--
		-- if jowner has been supplied, we may need to disable all scheduled jobs
		-- that are not owned by that user.
		--
		if @jowner is not NULL
		begin
			update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid
				where sjob_job_id=@job_id and sjob_owner != @jowner
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
	end
	if @sjob_id is not NULL
	begin
		update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
	end


	if @sched_id is not NULL
	begin
		--
		-- get the current values
		--
		select  @cur_sname=sched_name,	@cur_sdesc=sched_description,	@cur_sowner=sched_owner,
			@int_properties=sched_properties, @cur_uproperties=sched_uproperties,
			@cur_repeats=sched_interval,	@cur_units=sched_interval_units,
			@cur_startdate=sched_startdate,	@cur_starttime=sched_starttime,
			@cur_enddate=sched_enddate,	@cur_endtime=sched_endtime, 
			@cur_days=sched_days,		@cur_dates=sched_dates,
			@cur_udays=sched_udays,		@cur_udates=sched_udates,
			@cur_urepeats=sched_uinterval,	@cur_expired=sched_expired
		from sybmgmtdb..js_schedules where sched_id = @sched_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_schedules', @err
			return -@@error
		end
		--
		-- perform additional checks with schedule locked
		--
		if @is_admin = 0 and @cur_sowner != suser_name()
		begin
			rollback tran nested_tran
			commit tran
			-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
			raiserror 19084, @sp_name 
			return -@@error
		end
		if @sowner is not NULL	select @cur_sowner=@sowner
		if @sname is not NULL	select @cur_sname=@sname
		if @sproperties is not NULL
		begin
			--
			-- process property names
			--
			exec @err=sp_js_properties @int_properties, 'sched', @sproperties, @new_properties output, @cur_uproperties output
			if @err < 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@sproperties', @sproperties
				return -@@error
			end
			--
			-- reject un-share if currently used by other users
			--
			if (@int_properties & 32 = 32) and (@new_properties & 32 != 32)
			begin
				if exists (select sjob_sched_id from sybmgmtdb..js_scheduledjobs
					where sjob_sched_id=@sched_id and sjob_owner != @cur_sowner)
				begin
					rollback tran nested_tran
					commit tran
					-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
					select @vcname=@cur_sname
					raiserror 19079, @sp_name, @vcname
					return -@@error
				end
			end
			select @int_properties=@new_properties
		end
		-- 
		-- setup the new values in the schedule
		--
		if @sname is not NULL	select @cur_sname=@sname
		if @sdesc is not NULL	select @cur_sdesc=nullif(@sdesc, ' ')
		if @reset = 'true'
		begin
			select @cur_repeats=0, @cur_units=' ', @cur_startdate=getdate(), @cur_starttime=NULL,
				@cur_enddate=NULL, @cur_endtime=NULL, @cur_days=0, @cur_udays=NULL,
				@cur_dates=0, @cur_udates=NULL, @cur_urepeats=NULL,
				@tell_ase=1
		end
		if @repeats is not NULL	select @cur_repeats=@int_repeats, @cur_units=@int_units, @tell_ase=1
		set arithabort off	-- restored on return
		if @startdate is not NULL
		begin
			if @startdate = '' select @startdate=NULL
			select @cur_startdate=convert(datetime, @startdate)
			if @@error != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@startdate', @startdate
				return -@@error
			end
			select @tell_ase=1
		end
		if @starttime is not NULL
		begin
			if @starttime = '' select @starttime=NULL
			select @cur_starttime=convert(datetime, @starttime)
			if @@error != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@starttime', @starttime
				return -@@error
			end
			select @tell_ase=1
		end
		if @enddate is not NULL
		begin
			if @enddate = '' select @enddate=NULL
			select @cur_enddate=convert(datetime, @enddate)
			if @@error != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@enddate', @enddate
				return -@@error
			end
			select @tell_ase=1
		end
		if @endtime is not NULL
		begin
			if @endtime = '' select @endtime=NULL
			select @cur_endtime=convert(datetime, @endtime)
			if @@error != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@endtime', @endtime
				return -@@error
			end
			select @tell_ase=1
		end
		set arithabort on
		if @days  is not NULL	select @cur_udays=@days,   @tell_ase=1, @cur_days=NULL, @cur_dates=0, @cur_udates=NULL
		if @dates is not NULL	select @cur_udates=@dates, @tell_ase=1, @cur_dates=NULL, @cur_days=0, @cur_udays=NULL
		--
		-- validate the schedule timing
		--
		exec @err=sp_js_checksched @caller=@sp_name, @sname=@sname, @sdesc=@cur_sdesc,
				@sowner=@cur_sowner, @sched_id=@sched_id,
				@repeats=@cur_repeats, @units=@cur_units,
				@startdate=@cur_startdate, @starttime=@cur_starttime,
				@enddate=@cur_enddate, @endtime=@cur_endtime,
				@days=@cur_days, @dates=@cur_dates,
				@udays=@cur_udays, @udates=@cur_udates,
				@int_repeats=@int_repeats output, @int_units=@int_units output,
				@int_days=@int_days output, @int_dates=@int_dates output,
				@int_udays=@int_udays output, @int_udates=@int_udates output
		if @err < 0
		begin
			rollback tran nested_tran
			commit tran
			-- sp_js_checksched raises the error
			return @err
		end
		select @cur_urepeats=convert(varchar(32), @int_repeats) + @cur_units
		if (@cur_expired & 1) = 1	select @cur_expired=@cur_expired - 1
		--
		-- update
		--
		update sybmgmtdb..js_schedules set 
			sched_name=@cur_sname, sched_description=@cur_sdesc, sched_owner=@cur_sowner,
			sched_update=0, sched_properties=@int_properties,
			sched_interval=@int_repeats, sched_interval_units=@int_units,
			sched_startdate=@cur_startdate, sched_starttime=@cur_starttime,
			sched_enddate=@cur_enddate, sched_endtime=@cur_endtime,
			sched_days=@int_days, sched_dates=@int_dates,
			sched_udays=@int_udays, sched_udates=@int_udates,
			sched_uproperties=@cur_uproperties, sched_uinterval=@cur_urepeats, sched_expired=@cur_expired
		where sched_id=@sched_id
		select @err=@@error
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_schedules', @err
			return -@@error
		end
	end

	if @job_id is not NULL
	begin
		select @cur_jname=job_name, @cur_jdesc=job_description, @cur_jowner=job_owner,
			@int_properties=job_properties, @cur_uproperties=job_uproperties,
			@cur_tmpl_id=job_tmpl_id, @cur_default_timeout=job_default_timeout
		from sybmgmtdb..js_jobs where job_id=@job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_jobs', @err
			return -@@error
		end
		--
		if @is_admin = 0 and @cur_jowner != suser_name()
		begin
			rollback tran nested_tran
			commit tran
			-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
			raiserror 19084, @sp_name 
			return -@@error
		end
		select @prev_jowner=@cur_jowner		-- save the previous job_owner
		if @jowner is not NULL	select @cur_jowner=@jowner
		
		if @jname is not NULL
		begin
			-- Check job name does not already exist
			if exists (select job_name from sybmgmtdb..js_jobs
					where job_name = @jname and job_owner = @cur_jowner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19059 'Procedure %1!, a %2! already exists with the name %3!',
				select @vcname=@jname
				raiserror 19059, @sp_name, 'job', @vcname
				return -@@error
			end
			select @cur_jname=@jname
		end
		if @jdesc is not NULL	select @cur_jdesc=@jdesc
		if @jproperties is not NULL
		begin
			--
			-- build the new properties
			--
			exec @err=sp_js_properties @int_properties, 'job', @jproperties, @new_properties output, @cur_uproperties output
			if @err < 0
			begin
				rollback tran nested_tran
				commit tran
				-- -1 19088 'Procedure %1!, @properties=''%2!'', invalid property name or value.'
				-- -2 19089 'Procedure %1!, @properties=''%2!'', a property cannot be used with the scheduledjob, job or schedule.
				if @err = -1
					raiserror 19088, @sp_name, @jproperties
				else	raiserror 19089, @sp_name, @jproperties
				return -@@error
			end
			--
			-- Check if run_as_owner has been turned on
			--
			if (@int_properties & 2 != 2) and (@new_properties & 2 = 2)
			begin
				if @cur_jowner != suser_name()
				begin
					rollback tran nested_tran
					commit tran
					-- 19087 'Procedure %1!, only the owner of a job may set the run_as_owner property.'
					raiserror 19087, @sp_name
					return -@@error
				end
			end
			--
			-- Check if shared flag is being cleared.
			--
			if (@int_properties & 32 = 32) and (@new_properties & 32 != 32)
			begin
				--	
				-- reject if currently used by other users
				--
				if exists (select sjob_job_id from sybmgmtdb..js_scheduledjobs where sjob_job_id=@job_id and sjob_owner != @cur_jowner)
				begin
					rollback tran nested_tran
					commit tran
					-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
					select @vcname=@jname
					raiserror 19079, @sp_name, @vcname
					return -@@error
				end
			end
			select @int_properties=@new_properties
		end
		if @prev_jowner != @cur_jowner
		begin
			--
			-- Only a privileged user can check the roles granted to another user,
			-- so we cannot see if the new owner has js_user_role or js_admin_role role.
			-- Therefore we clear run_as_owner property when owner is changed.
			--
			exec @err=sp_js_properties @int_properties, 'job', 'run_as_owner=false', @new_properties output, @cur_uproperties output
			if @err = 0 select @int_properties=@new_properties
			select @cur_jowner=@jowner
		end
		if @default_timeout is not NULL	select @cur_default_timeout=@default_timeout
		if @tmpl_id is not NULL		select @cur_tmpl_id=@tmpl_id
		--
		-- update
		--
		if @jcmd is not NULL
		begin
			if @cur_jowner != suser_name()
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name 
				return -@@error
			end
			delete from sybmgmtdb..js_commands where jcmd_job_id = @job_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19073 'Procedure %1!, failed to delete an entry in the %2! table, delete error %3!.'
				raiserror 19073, @sp_name, 'js_commands', @err
				return -@@error
			end
			select @seqno=0, @curpos=1, @len=isnull(char_length(@jcmd), 0), @err=0
			while @curpos <= @len and @err = 0
			begin
				select @chunk=substring(@jcmd, @curpos, 900) + char(10)
				insert sybmgmtdb..js_commands (jcmd_job_id, jcmd_type, jcmd_seqno, jcmd_text)
					values (@job_id, 0, @seqno, @chunk)
				select @err=@@error, @rows=@@rowcount
				select @seqno=@seqno+1, @curpos=@curpos + 900
			end
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
				raiserror 19075, @sp_name, 'js_commands', @err
				return -@@error
			end
		end
		update sybmgmtdb..js_jobs set job_name=@cur_jname, job_description=@cur_jdesc, job_owner=@cur_jowner,
			job_update=0, job_properties=@int_properties,
			job_default_timeout=@cur_default_timeout, job_tmpl_id=@cur_tmpl_id,
			job_uproperties=@cur_uproperties
	 	where job_id=@job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
	end
	if @sjob_id is not NULL
	begin
		select @cur_sjname=sjob_name, @cur_sjowner=sjob_owner,
			@int_properties=sjob_properties, @cur_uproperties=sjob_uproperties,
			@cur_enable=sjob_enable, @cur_server=sjob_server,
			@cur_locale=sjob_locale, @cur_timeout=sjob_timeout_value
		from sybmgmtdb..js_scheduledjobs where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		-- check permision
		if @is_admin = 0 and @cur_sjowner != suser_name()
		begin
			rollback tran nested_tran
			commit tran
			-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
			raiserror 19084, @sp_name 
			return -@@error
		end
		-- Only the owner can enable a disabled scheduled job.
		if @enable is not NULL
		begin
			if @cur_enable = 0 and @enable = 1 and @cur_sjowner != suser_name()
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name
				return -@@error
			end
			select @cur_enable=@enable
		end
		--
		-- Only a privileged user can check the roles granted to another user, so we 
		-- cannot see if the new owner has js_user_role or js_admin_role role. Therefore, we
		-- disable the scheduled job and the new job owner will have to re-enable it.
		--
		if @sjowner is not NULL
		begin
			if @cur_sjowner != @sjowner select @cur_enable=0
			select @cur_sjowner=@sjowner
		end
		
		if @sjname is not NULL
		begin
			-- Check job name does not already exist
			if exists (select sjob_name from sybmgmtdb..js_scheduledjobs
					where sjob_name = @sjname and sjob_owner = @cur_sjowner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19059 'Procedure %1!, a %2! already exists with the name %3!',
				select @vcname=@sjname
				raiserror 19059, @sp_name, 'scheduled job', @vcname
				return -@@error
			end
			select @cur_sjname=@sjname
		end
		if @server is not NULL	select @cur_server=nullif(@server, '')
		if @locale is not NULL	select @cur_locale=nullif(@locale, '')
		if @timeout is not NULL select @cur_timeout=@timeout
		if @properties is not NULL
		begin
			--
			-- build the new properties
			--
			exec @err=sp_js_properties @int_properties, 'sjob', @properties, @new_properties output, @cur_uproperties output
			if @err < 0
			begin
				rollback tran nested_tran
				commit tran
				-- -1 19088 'Procedure %1!, @properties=''%2!'', invalid property name or value.'
				-- -2 19089 'Procedure %1!, @properties=''%2!'', a property cannot be used with the scheduledjob, job or schedule.
				if @err = -1
					raiserror 19088, @sp_name, @properties
				else	raiserror 19089, @sp_name, @properties
				return -@@error
			end
			--
			-- Currently none of the scheduledjobs properties requires any checks
			-- or action when they are set or cleared.
			select @int_properties=@new_properties
		end
		update sybmgmtdb..js_scheduledjobs set sjob_name=@cur_sjname, sjob_owner=@cur_sjowner,
			sjob_update=0, sjob_properties=@int_properties,
			sjob_enable=@cur_enable, sjob_server=@cur_server,
			sjob_locale=@cur_locale, sjob_timeout_value=@cur_timeout,
			sjob_uproperties=@cur_uproperties
	 	where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
	end
	if @job_id is not NULL
	begin
		--
		-- disable all scheduled jobs using this job that are not owned by
		-- the new owner.
		--
		if @prev_jowner != @cur_jowner
		begin
			update sybmgmtdb..js_scheduledjobs set sjob_update=0, sjob_enable=0
				where sjob_job_id=@job_id and sjob_owner != @jowner
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
	end

	commit tran
	--
	-- After the updates are done, inform the ASE task about:
	--	the enabling or disabling of a scheduled job
	--	the disabling of scheduled jobs due to job_owner change.
	--	and each scheduled job affected by a modified schedule.
	-- 
	if @sjob_id is not NULL
	begin
		if @enable=0 and @cur_enable=1
			exec sp_js_wakeup 'job_disabled', @sjob_id
		else if @enable=1 and @cur_enable=0
			exec sp_js_wakeup 'job_enabled', @sjob_id
	end
	if @job_id is not NULL and @prev_jowner != @cur_jowner
	begin
		--
		-- disable all scheduled jobs using this job that are not owned by
		-- the new owner.
		--
		select @id=sjob_id from sybmgmtdb..js_scheduledjobs
			where sjob_job_id=@job_id and sjob_owner != @cur_jowner and sjob_enable=0
		select @tell_ase=@@rowcount
		if @tell_ase = 1
		begin
			exec sp_js_wakeup 'job_disabled', @id
		end
		else if @tell_ase > 1
		begin
			declare new_jowner cursor for select sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_job_id=@job_id and sjob_owner != @cur_jowner and sjob_enable=0
				for read only
			open new_jowner
			fetch new_jowner into @sjob_id
			while @@sqlstatus = 0
			begin
				exec sp_js_wakeup 'job_disabled', @sjob_id
				fetch new_jowner into @sjob_id
			end
			close new_jowner
			deallocate cursor new_jowner
		end
	end
	if @tell_ase != 0
	begin
		select @id=sjob_id from sybmgmtdb..js_scheduledjobs where sjob_sched_id=@sched_id and sjob_enable=1
		select @tell_ase=@@rowcount
		if @tell_ase = 1
		begin
			exec sp_js_wakeup 'new_schedule', @id
			return 0
		end
		declare new_sched cursor for select sjob_id from sybmgmtdb..js_scheduledjobs
			where sjob_sched_id=@sched_id and sjob_enable=1
			for read only
		open new_sched
		fetch new_sched into @sjob_id
		while @@sqlstatus = 0
		begin
			exec sp_js_wakeup 'new_schedule', @sjob_id
			fetch new_sched into @sjob_id
		end
		close new_sched
		deallocate cursor new_sched
	end

	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobmodify')
begin
	print 'Created sp_sjobmodify'
	grant execute on sp_sjobmodify to js_user_role
	grant execute on sp_sjobmodify to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_sjobcreate')
	drop proc sp_sjobcreate
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobcreate  @name univarchar(),  @option univarchar()
--
--      @name is the name of the scheduled job, job or schedule to
--      be created.
--      The selection is made by using a prefix of sjname=, jname= or sname=.
--      With no prefix the default is the name or id of a scheduled job.
--      Example:-
--              'sjname=scheduled_job_name'
--              'jname=job_name'
--              'sname=schedule_name'
--
--      @option is a list of name value pairs.
--
create proc sp_sjobcreate (
	@name		univarchar(128),
	@option		univarchar(4000) = NULL
)
as
begin
	declare @opt_val_pair univarchar(512), @opt_name univarchar(512), @opt_value univarchar(512)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @sp_name varchar(32), @name_value univarchar(64), @tell_ase int
	declare @err int, @rows int, @msgno int, @is_admin int
	declare @sjob_id int, @job_id int, @sched_id int, @sj_opt int, @j_opt int, @s_opt int, @id int
	declare @int_sjprops int, @int_sprops int, @int_jprops int, @new_props int
	declare @u_sjprops varchar(128), @u_sprops varchar(128), @u_jprops varchar(128)
	declare @cur_job_id int, @cur_sched_id int, @opt_count int, @create_sched int, @create_job int
	declare @int_udays varchar(128), @int_udates varchar(128), @seqno int, @chunk univarchar(901)
	--
	declare @created datetime
	declare @int_repeats int, @int_units char(1), @int_days int, @int_dates int
	--
	-- scheduled job values
	--
	declare @sjname univarchar(64), @enable int, @properties varchar(128), @owner varchar(30)
	declare @server varchar(30), @timeout int, @locale varchar(30)
	-- job values
	declare @jname univarchar(64), @jdesc univarchar(128), @jcmd univarchar(1801), @jproperties varchar(128)
	declare @jowner varchar(30), @default_timeout int, @tmpl_id int
	-- schedule values
	declare @sname univarchar(64), @sdesc univarchar(128), @sproperties varchar(128), @sowner varchar(30)
	declare @repeats varchar(32), @startdate datetime, @starttime datetime
	declare @enddate datetime, @endtime datetime, @days varchar(128), @dates varchar(128)
	-- 
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select @sp_name='sp_sjobcreate'
	select @tell_ase=0, @sj_opt=0, @j_opt=0, @s_opt=0, @cur_job_id=0, @cur_sched_id=0, @opt_count=0
	select @create_job=0, @create_sched=0, @int_sjprops=0, @int_jprops=0, @int_sprops=0
	select @default_timeout=0, @timeout=0, @int_repeats=0, @int_units=' ', @int_days=0, @int_dates=0

	select @is_admin=proc_role('js_admin_role')
	--
	-- Get and validate the name or id of the scheduled job, job or schedule.
	--
	select @opt_val_pair = ltrim(rtrim(@name))
	select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)
	if @eq_pos <= 0				-- no prefix, defaults to scheduled job
		select @opt_name='sjname', @opt_value=@opt_val_pair
	else if @eq_pos = @opt_val_len		-- opt_name=  error
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	else
	begin
		select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
		select @opt_name=ltrim(rtrim(@opt_name))
		select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
		select @opt_value = ltrim(rtrim(@opt_value))
	end
	select @sjob_id=NULL, @job_id=NULL, @sched_id=NULL
	if @opt_name = 'sjname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=0, @table='sjob_'
		select @sjob_id=0, @name_value=@opt_value
	end
	else if @opt_name = 'jname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=0, @table='job_'
		select @job_id=0, @name_value=@opt_value
	end
	else if @opt_name = 'sname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=0, @table='sched_'
		select @sched_id=0, @name_value=@opt_value
	end
	else
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	if @id < 0
	begin
		select @msgno = abs(@id)
		raiserror @msgno, @sp_name, '@name'
		return -@@error
	end
	--
	-- Setup defaults values
	--
	select @owner=suser_name(), @startdate=getdate(), @starttime=NULL, @enddate=NULL, @endtime=NULL
	select @jowner=@owner, @sowner=@owner, @enable=1, @created=@startdate
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @option=ltrim(rtrim(@option))
	select @len=isnull(char_length(@option), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @option)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @option=stuff(@option, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @option=stuff(@option, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@option, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		--
		-- scheduled job options
		--	sjname, enable, properties, owner, server, timeout, locale
		-- job options
		--	jname, jdesc, jcmd, jproperties, jowner, default_timeout, tmpl_id
		-- schedule schedule
		--	sname, sdesc, sowner, sproperties, repeats,
		--	startdate, starttime, enddate, endtime, days, dates
		--
		if      @opt_name = 'sjname'		select @sjname=@opt_value
		else if @opt_name = 'server'		select @server=@opt_value, @sj_opt=1
		else if @opt_name = 'locale'		select @locale=@opt_value, @sj_opt=1
		else if @opt_name = 'jname'		select @jname=@opt_value
		else if @opt_name = 'jdesc'		select @jdesc=@opt_value, @j_opt=1
		else if @opt_name = 'jdescription'	select @jdesc=@opt_value, @j_opt=1
		else if @opt_name = 'sname'		select @sname=@opt_value
		else if @opt_name = 'sdesc'		select @sdesc=@opt_value, @s_opt=1
		else if @opt_name = 'sdescription'	select @sdesc=@opt_value, @s_opt=1
		else if @opt_name = 'repeats'		select @repeats=@opt_value, @s_opt=1
		else if @opt_name = 'startdate'		select @startdate=convert(datetime, @opt_value), @s_opt=1
		else if @opt_name = 'starttime'		select @starttime=convert(datetime, @opt_value), @s_opt=1
		else if @opt_name = 'enddate'		select @enddate=convert(datetime, @opt_value), @s_opt=1
		else if @opt_name = 'endtime'		select @endtime=convert(datetime, @opt_value), @s_opt=1
		else if @opt_name = 'days'		select @days=@opt_value, @s_opt=1
		else if @opt_name = 'dates'		select @dates=@opt_value, @s_opt=1
		else if @opt_name = 'jcmd'
		begin
			-- opt_val_pair is only 512, so re-select into @jcmd
			select @jcmd=substring(@option, @curpos, @end_pos-@curpos)
			select @eq_pos=patindex('%=%', @jcmd)
			select @jcmd=substring(@jcmd, @eq_pos + 1, @end_pos-@curpos), @j_opt=1
		end
		else if @opt_name = 'enable'
		begin
			if @opt_value = 'true' or @opt_value = '1'	 select @enable=1, @sj_opt=1
			else if @opt_value = 'false' or @opt_value = '0' select @enable=0, @sj_opt=1
			else
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
                		select @vcbuf1=@opt_name, @vcbuf2=@opt_value
				raiserror 19070, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @opt_name = 'properties' or @opt_name = 'sjproperties' or
			@opt_name = 'jproperties' or @opt_name = 'sproperties'
		begin
			if @opt_name = 'properties' or @opt_name = 'sjproperties'
			begin
				exec @err=sp_js_properties @int_sjprops, 'sjob2', @opt_value, @int_sjprops output, @u_sjprops output
				if @err != -1
					exec @err=sp_js_properties @int_jprops, 'job2', @opt_value, @int_jprops output, @u_jprops output
			end
			else if @opt_name = 'jproperties'
				exec @err=sp_js_properties @int_jprops, 'job', @opt_value, @int_jprops output, @u_jprops output
			else	exec @err=sp_js_properties @int_sprops, 'sched', @opt_value, @int_sprops output, @u_sprops output

			if @err < 0
			begin
				-- -1 19088 'Procedure %1!, @properties=''%2!'', invalid property name or value.'
				-- -2 19089 'Procedure %1!, @properties=''%2!'', a property cannot be used with the scheduledjob, job or schedule.
				select @vcbuf1=@opt_value
				if @err = -1
					raiserror 19088, @sp_name, @vcbuf1
				else	raiserror 19089, @sp_name, @vcbuf1
				return -@@error
			end
			if      @opt_name = 'properties'	select @properties=@opt_value, @sj_opt=1
			else if @opt_name = 'sjproperties'	select @properties=@opt_value, @sj_opt=1
			else if @opt_name = 'jproperties'	select @jproperties=@opt_value, @j_opt=1
			else					select @sproperties=@opt_value, @s_opt=1
		end
		else if @opt_name = 'owner' or @opt_name = 'jowner' or @opt_name = 'sowner'
		begin
			if @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			--
			-- Validate server username
			--
			if suser_id(@opt_value) is NULL
			begin
				-- 19080 'Procedure %1!, %2! is not a valid server username.'
				select @vcbuf1=@opt_value
				raiserror 19080, @sp_name, @vcbuf1
				return -@@error
			end
			if      @opt_name = 'owner'  select @owner=@opt_value, @sj_opt=1
			else if @opt_name = 'jowner' select @jowner=@opt_value, @j_opt=1
			else			     select @sowner=@opt_value, @s_opt=1
		end
		else if @opt_name = 'timeout' or @opt_name = 'default_timeout' or @opt_name = 'tmpl_id'
		begin
			-- check that the value is a +ve integer
			exec @err=sp_js_check_id @name_id=@opt_value, @cmd=3
			if @err < 0
			begin
				-- 19060 'Procedure %1!, %2! must be a positive integer.'
				-- raiserror 19060, @sp_name, @opt_name
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
                		select @vcbuf1=@opt_name, @vcbuf2=@opt_value
				raiserror 19070, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			if      @opt_name = 'timeout'		select @timeout=@err, @sj_opt=1
			else if @opt_name = 'default_timeout'	select @default_timeout=@err, @j_opt=1
			else					select @tmpl_id=@err, @j_opt=1
		end
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
                	select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end
		select @curpos=@end_pos + 1, @opt_count=@opt_count + 1
	end

	if @sjob_id is NULL
	begin
		-- 19092 'Procedure %1!, the name or id of a scheduled job or a job is needed when options for jobs are supplied.'
		-- 19093 'Procedure %1!, the name or id of a scheduled job or a schedule is needed when options for schedules are supplied.'
		-- 19094 'Procedure %1!, the name or id of a scheduled job is needed when options for schedulejobs are supplied.'
		if      @sj_opt = 1			select @msgno=19094
		else if @job_id   is NULL and @j_opt = 1	select @msgno=19092
		else if @sched_id is NULL and @s_opt = 1	select @msgno=19093
		else select @msgno=0
		if @msgno != 0
		begin
			raiserror @msgno, @sp_name
			return -@@error
		end
	end
	--
	-- reset the name of the scheduled job, job or schedule from the @name argument
	--
	if @sjob_id = 0  select @sjname=@name_value
	if @job_id = 0   select @jname=@name_value
	if @sched_id = 0 select @sname=@name_value
	
	-- Validate the name for a new job
	if @job_id = 0
	begin
		select @create_job=1
		if exists (select job_id from sybmgmtdb..js_jobs where job_name = @jname and job_owner = @jowner)
		begin
			-- 19059 'Procedure %1!, a %2! entry already exists with the name %3!.'
			select @vcname=@jname
			raiserror 19059, @sp_name, 'job', @vcname
			return -@@error
		end
	end
	-- Validate the name for a new schedule
	if @sched_id = 0
	begin
		select @create_sched=1
		if exists (select sched_id from sybmgmtdb..js_schedules where sched_name = @sname and sched_owner = @sowner)
		begin
			-- 19059 'Procedure %1!, a %2! entry already exists with the name %3!.'
			select @vcname=@sname
			raiserror 19059, @sp_name, 'schedule', @vcname
			return -@@error
		end
	end
	if @sjob_id = 0
	begin
		if exists (select sjob_id from sybmgmtdb..js_scheduledjobs where sjob_name = @sjname and sjob_owner = @owner)
		begin
			-- 19059 'Procedure %1!, a %2! entry already exists with the name %3!.'
			select @vcname=@sjname
			raiserror 19059, @sp_name, 'scheduledjob', @vcname
			return -@@error
		end
		--
		-- Work out if we are combining an existing job or schedule or defining new ones.
		-- We do not protect against existing schedule or job being deleted before the
		-- scheduledjob gets created - that is taken care of with the references.
		if @jname is NULL
		begin
			select @create_job=1, @cur_job_id=NULL
		end
		else if substring(@jname, 1, 1) like '[0-9]'
		begin
			-- if @jname is an id, it must exist
			exec @err=sp_js_check_id @name_id=@jname, @cmd=1, @table='job', @return_id=1, @is_admin=@is_admin
			if @err < 0
			begin
				select @msgno = abs(@err), @vcname=@jname
				raiserror @msgno, @sp_name, @vcname
				return -@@error
			end
			select @cur_job_id=@err
		end
		else
		begin
			--
			-- if @jname is a name that exists, we will try to use it
			--
			-- catch 22 for admin users, if they want to create their own 'myjob' and 
			-- other users have 'myjob' jobs - so we set @is_admin=0
			--
			if @j_opt = 1
			exec @err=sp_js_check_id @name_id=@jname, @cmd=0, @table='job', @return_id=1, @is_admin=0
			else
			exec @err=sp_js_check_id @name_id=@jname, @cmd=0, @table='job', @return_id=1, @is_admin=@is_admin
			if @err = -19097	-- non unique name
			begin
				select @msgno = abs(@err), @vcname=@jname
				raiserror @msgno, @sp_name, @vcname
				return -@@error
			end
			if @err < 0
			begin
				-- if it doesn't exist, validate it
				exec @err=sp_js_check_id @name_id=@jname, @cmd=0, @table='job_'
				if  @err < 0
				begin
					select @msgno = abs(@err), @vcname=@jname
					raiserror @msgno, @sp_name, @vcname
					return -@@error
				end
				select @create_job=1, @cur_job_id=NULL
			end
			else select @cur_job_id=@err
		end
		if @cur_job_id is not NULL
		begin
			-- if there is a shared job with that name, create another one rather than error.
			if @j_opt != 0
			begin
				if exists (select job_id from sybmgmtdb..js_jobs
							where job_id=@cur_job_id and job_owner = suser_name())
				begin
					-- 19095 'Procedure %1!, cannot modify job fields in an existing job.'
					raiserror 19095, @sp_name
					return -@@error
				end
				select @create_job=1, @cur_job_id=NULL
			end
		end
	
		if @sname is NULL
		begin
			select @create_sched=1, @cur_sched_id=NULL
		end
		else if substring(@sname, 1, 1) like '[0-9]'
		begin
			-- if @sname is an id, it must exist
			exec @err=sp_js_check_id @name_id=@sname, @cmd=1, @table='sched', @return_id=1, @is_admin=@is_admin
			if @err < 0
			begin
				select @msgno = abs(@err), @vcname=@sname
				raiserror @msgno, @sp_name, @vcname
				return -@@error
			end
			select @cur_sched_id=@err
		end
		else
		begin
			-- if @sname is a name that exists, we will use it
			exec @err=sp_js_check_id @name_id=@sname, @cmd=0, @table='sched', @return_id=1, @is_admin=0
			if @err = -19097	-- non unique name
			begin
				select @msgno = abs(@err), @vcname=@sname
				raiserror @msgno, @sp_name, @vcname
				return -@@error
			end
			if @err < 0
			begin
				-- if it doesn't exist, validate it
				exec @err=sp_js_check_id @name_id=@sname, @cmd=0, @table='sched_'
				if  @err < 0
				begin
					select @msgno = abs(@err), @vcname=@sname
					raiserror @msgno, @sp_name, @vcname
					return -@@error
				end
				select @create_sched=1, @cur_sched_id=NULL
			end
			else select @cur_sched_id=@err
		end
		if @cur_sched_id is not NULL
		begin
			-- if there is a shared schedule with that name, create another one rather than error.
			if @s_opt != 0
			begin
				if exists (select sched_id from sybmgmtdb..js_schedules
						where sched_id=@cur_sched_id and sched_owner = suser_name())
				begin
					-- 19096 'Procedure %1!, cannot modify schedule fields in an existing schedule.'
					raiserror 19096, @sp_name
					return -@@error
				end
				select @create_sched=1, @cur_sched_id=NULL
			end
		end
	end

	--
	-- Only a privileged user can check the roles granted to another user, so we cannot see
	-- if the new owner of the scheduled job has js_user_role or js_admin_role role.
	--
	-- Therefore we disable the scheduled job and the job owner will have to
	-- enable it. For a new job clear the run_as_owner
	--
	if @owner != suser_name()
		select @enable=0
	if @jowner != suser_name() and (@int_jprops & 2 = 2)
	begin
		exec @err=sp_js_properties @int_jprops, 'job', 'run_as_owner=false', @new_props output, @u_jprops output
		if @err = 0 select @int_jprops=@new_props
	end
	--
	-- Validate the various fields, now that we know what we are creating
	--
	if @s_opt != 0
	begin
		if @repeats is NULL or @repeats = '0'
			select @int_repeats=0, @int_units=' '
		else
		begin
			select @pos=patindex('%[^-0-9]%', @repeats)
			if @pos is NULL or @pos < 1
			begin
				select @int_units='m'
				exec @int_repeats=sp_js_check_id @name_id=@repeats, @cmd=3
			end
			else
			begin
				select @opt_val_pair=substring(@repeats, @pos, isnull(char_length(@repeats), 0) - @pos + 1)
				select @int_units=case @opt_val_pair
				when 'days'    then 'd' when 'day'    then 'd' when 'dd' then 'd' when 'd' then 'd'
				when 'hours'   then 'h' when 'hour'   then 'h' when 'hh' then 'h' when 'h' then 'h'
				when 'minutes' then 'm' when 'minute' then 'm' when 'mm' then 'm' when 'm' then 'm'
				else '-'
				end
				if @int_units = '-'
				begin
					-- 19062 'Procedure %1!, units must be days, hours, minutes, dd, mm, hh, d, h or m.'
					raiserror 19062, @sp_name
					return -@@error
				end
				select @opt_val_pair=substring(@repeats, 1, @pos - 1)
				exec @int_repeats=sp_js_check_id @name_id=@opt_val_pair, @cmd=3
			end
			if @int_repeats = 0
			begin
				select @int_units=' '
			end
		end
		if @int_repeats < 0
		begin
			-- 19060 'Procedure %1!, %2! must be a positive integer.'
			raiserror 19060, @sp_name, 'repeats'
			return -@@error
		end
		select @repeats=@opt_value, @s_opt=1

		--
		-- validate the schedule timing
		--
		exec @err=sp_js_checksched @caller=@sp_name, @sname=@sname, @sdesc=@sdesc,
				@sowner=@sowner, @sched_id=NULL,
				@repeats=@int_repeats, @units=@int_units,
				@startdate=@startdate, @starttime=@starttime,
				@enddate=@enddate, @endtime=@endtime,
				@days=NULL,  @dates=NULL,
				@udays=@days, @udates=@dates,
				@int_repeats=@int_repeats output, @int_units=@int_units output,
				@int_days=@int_days output, @int_dates=@int_dates output,
				@int_udays=@int_udays output, @int_udates=@int_udates output
		if @err < 0
		begin
			-- sp_js_checksched raises the error
			return @err
		end
	end
	--
	-- Generate all the keys needed for the scheduled job, job and schedule
	--
	if @create_sched = 1
	begin
		exec @sched_id=sp_js_getkey 'sched_id'
		if @sched_id < 0
		begin
			select @msgno=abs(@sched_id)
			raiserror @msgno, @sp_name, 'sched_id'
			return -@@error
		end
	end
	else select @sched_id=0

	if @create_job = 1
	begin
		exec @job_id=sp_js_getkey 'job_id'
		if @job_id < 0
		begin
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			select @msgno=abs(@job_id)
			raiserror @msgno, @sp_name, 'job_id'
			return -@@error
		end
	end
	else select @job_id=0

	if @sjob_id = 0
	begin
		exec @sjob_id=sp_js_getkey 'sjob_id'
		if @sjob_id < 0
		begin
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			select @msgno=abs(@sjob_id)
			raiserror @msgno, @sp_name, 'sjob_id'
			return -@@error
		end
	
		if @sname is NULL or @sname = ''
			select @sname='sched_' + convert(varchar(32), @sched_id)
		if @jname is NULL or @jname = ''
			select @jname='job_' + convert(varchar(32), @job_id)
	end
	else select @sjob_id = 0
	--
	--
	begin tran sp_sjobcreate
	save tran nested_tran
	--
	-- NOTE: the updates are in the following order
	--		js_schedules
	--		js_jobs
	--		js_cmds
	--		js_scheduledjobs
	--
	-- ALL TRANSACTIONS WITHIN THE STORED PROCEDURES THAT UPDATE MORE THAN ONE
	-- TABLE (e.g. sp_sjobmodify) MUST LOCK THE TABLES IN THE SAME ORDER.
	--
	select @err=0
	if @create_sched = 1
	begin
		insert sybmgmtdb..js_schedules
			(sched_id, sched_update, sched_type, sched_properties, sched_owner, sched_created,
			sched_interval, sched_interval_units,
			sched_startdate, sched_starttime, sched_enddate, sched_endtime,
			sched_days, sched_dates, sched_name, sched_description, 
			sched_uproperties, sched_uinterval, sched_udays, sched_udates, sched_expired)
		values (@sched_id, 0, 0, @int_sprops, @sowner, @created,
			@int_repeats, @int_units,
			@startdate, @starttime, @enddate, @endtime,
			@int_days, @int_dates, @sname, @sdesc,
			@u_sprops, convert(varchar(32), @int_repeats) + @int_units, @int_udays, @int_udates, 0)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_schedules', @err
			return -@@error
		end
	end
	else if @sjob_id != 0
	begin
		-- update lock the schedule
		update sybmgmtdb..js_schedules set sched_update=@@spid where sched_id=@cur_sched_id
		select @err=@@error, @rows=@@rowcount
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		-- 19051 "Procedure %1!, parameter %2!, the specified schedule does not exist."
		-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
		if @err != 0		select @msgno=19074
		else if @rows != 1	select @msgno=19051
		else if not exists (select sched_id from sybmgmtdb..js_schedules where sched_id=@cur_sched_id and
					(sched_owner=suser_name() or (sched_properties & 32 = 32)) )
			select @err=1, @msgno=19083
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			if @msgno = 19074
				raiserror 19074, @sp_name, 'js_schedules', @err
			else if @msgno = 19051
			begin
				select @vcname=@sname
				raiserror 19051, @sp_name, @vcname
			end
			else	raiserror 19083, @sp_name, @cur_sched_id
			return -@@error
		end
	end

	if @create_job = 1
	begin
		insert sybmgmtdb..js_jobs
			(job_id, job_update, job_type, job_properties, job_owner, job_created,
			job_default_timeout, job_tmpl_id, job_name, job_description, job_uproperties)
		values (@job_id, 0, 0, @int_jprops, @jowner, @created,
			@default_timeout, @tmpl_id, @jname, @jdesc, @u_jprops)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_jobs', @err
			return -@@error
		end
		--
		-- create row in the js_commands table
		--
		select @seqno=0, @curpos=1, @len=isnull(char_length(@jcmd), 0), @err=0
		if @len = 0
		begin
			insert sybmgmtdb..js_commands (jcmd_job_id, jcmd_type, jcmd_seqno, jcmd_text)
				values (@job_id, 0, @seqno, NULL)
			select @err=@@error, @rows=@@rowcount
		end
		while @curpos <= @len and @err = 0
		begin
			select @chunk=substring(@jcmd, @curpos, 900) + char(10)
			insert sybmgmtdb..js_commands (jcmd_job_id, jcmd_type, jcmd_seqno, jcmd_text)
				values (@job_id, 0, @seqno, @chunk)
			select @err=@@error, @rows=@@rowcount
			select @seqno=@seqno+1, @curpos=@curpos + 900
		end
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_commands', @err
			return -@@error
		end
	end
	else if @sjob_id != 0
	begin
		-- update lock the job
		update sybmgmtdb..js_jobs set job_update=@@spid where job_id=@cur_job_id
		select @err=@@error, @rows=@@rowcount
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		-- 19050 "Procedure %1!, parameter %2!, the specified job does not exist."
		-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
		if @err != 0		select @msgno=19074
		else if @rows != 1	select @msgno=19050
		else if not exists (select job_id from sybmgmtdb..js_jobs where job_id=@cur_job_id and 
						(job_owner=suser_name() or (job_properties & 32 = 32)) )
			select @err=1, @msgno=19083
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			if @msgno = 19074
				raiserror 19074, @sp_name, 'js_commands', @err
			else if @msgno = 19050
			begin
				select @vcname=@jname
				raiserror 19050, @sp_name, @vcname
			end
			else	raiserror 19083, @sp_name, @cur_job_id
			return -@@error
		end
	end

	if @sjob_id != 0
	begin
		if @create_job = 1	select @cur_job_id=@job_id
		if @create_sched = 1	select @cur_sched_id=@sched_id
		insert sybmgmtdb..js_scheduledjobs
			(sjob_id, sjob_job_id, sjob_sched_id, sjob_update, sjob_enable, sjob_properties,
				sjob_created, sjob_timeout_value, sjob_owner, sjob_server,
				sjob_locale, sjob_name, sjob_uproperties)
		values (@sjob_id, @cur_job_id, @cur_sched_id, 0, @enable, @int_sjprops,
				@created, @timeout, @owner, @server,
				@locale, @sjname, @u_sjprops)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
	end
	if @create_job = 0
	begin
		-- unlock the job
		update sybmgmtdb..js_jobs set job_update=0 where job_id=@cur_job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
	end
	if @create_sched = 0
	begin
		-- unlock the schedule
		update sybmgmtdb..js_schedules set sched_update=0 where sched_id=@cur_sched_id
		select @err=@@error, @rows=@@rowcount
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			if @sjob_id  != 0	exec sp_js_putkey 'sjob_id', @sjob_id
			if @job_id   != 0	exec sp_js_putkey 'job_id', @job_id
			if @sched_id != 0	exec sp_js_putkey 'sched_id', @sched_id
			raiserror 19074, @sp_name, 'js_schedules', @err
			return -@@error
		end
	end
	commit tran
	--
	if @sjob_id != 0
	begin
		-- inform the ASE task
		exec sp_js_wakeup 'job_created', @sjob_id
		return @sjob_id
	end
	if @create_job = 1
		return @job_id
	if @create_sched = 1
		return @sched_id
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobcreate')
begin
	print 'Created sp_sjobcreate'
	grant execute on sp_sjobcreate to js_user_role
	grant execute on sp_sjobcreate to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_sjobcmd')
	drop proc sp_sjobcmd
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobcmd  @name univarchar(),  @option univarchar(),  @text varchar()
--
--      @name is the name or id of a scheduled job or job.
--      The selection is made by using a prefix of sjname= or jname=.
--      With no prefix the default is the name or id of a scheduled job.
--      Example:-
--              'sjname=scheduled_job_name'
--              'jname=job_name'
--
--      @option is the action to perform, 'list', 'add', 'drop'
--	Callers with the js_admin_role may also specify the 'all_users' option
--	when the action is 'list'.
--
create proc sp_sjobcmd (
	@name		univarchar(128),
	@option		univarchar(512)	= NULL,
	@text		univarchar(8000) = NULL
)
as
begin
	declare @opt_val_pair univarchar(512), @opt_name univarchar(512), @opt_value univarchar(512)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128), @vc_conv int
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int, @is_admin int
	declare @err int, @rows int, @msgno int, @job_id int, @sjob_id int, @id int, @seqno int, @all_users int
	declare @cmd varchar(8), @chunk univarchar(901), @owner varchar(30)
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobcmd', @cmd='list', @all_users=0, @vc_conv=1

	select @is_admin=proc_role('js_admin_role')
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @option=ltrim(rtrim(@option))
	select @len=isnull(char_length(@option), 0), @curpos=1
	if @len > 0
	begin
		select	@text = ' ' + @text + ' '
	end
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @option)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @option=stuff(@option, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @option=stuff(@option, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@option, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			select @opt_name = ltrim(rtrim(@opt_val_pair))
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		--
		if      @opt_name = 'list'	select @cmd='list'
		else if @opt_name = 'add'	select @cmd='add'
		else if @opt_name = 'drop'	select @cmd='drop'
		else if @opt_name = 'all_users'
		begin
			-- 19077 'Procedure %1!, only a user with the role js_admin_role can specify the owner or all_users.'
			if @is_admin = 0
			begin
				raiserror 19077, @sp_name
				return -@@error
			end
			select @all_users=1
		end
		else if @opt_name = 'sp_name'	select @sp_name=@opt_value
		else if @opt_name = 'varchar' or @opt_name = 'ascii'	select @vc_conv=1
		else if @opt_name = 'unichar' or @opt_name = 'utf8'	select @vc_conv=0
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
                	select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end
		select @curpos=@end_pos + 1
	end
	--
	-- Get and validate the name or id of the scheduled job or job.
	--
	select @opt_val_pair = ltrim(rtrim(@name))
	select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)

	if @eq_pos <= 0			-- no prefix, defaults to scheduled job
		select @opt_name='sjname', @opt_value=@opt_val_pair
	else if @eq_pos = @opt_val_len	-- name=  error
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	else
	begin
		select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
		select @opt_name=ltrim(rtrim(@opt_name))
		select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
		select @opt_value = ltrim(rtrim(@opt_value))
	end

	if @opt_name = 'sjname'
	    if @all_users = 1
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
	    else
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=0
	else if @opt_name = 'jname'
	    if @all_users = 1
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
	    else
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=0
	else
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	if @id < 0 
	begin
		select @msgno = abs(@id), @vcbuf1=@name
		raiserror @msgno, @sp_name, @vcbuf1
		return -@@error
	end
	else if @opt_name = 'sjname'
	begin
		-- get the job id
		select @job_id=sjob_job_id from sybmgmtdb..js_scheduledjobs where sjob_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
	end
	else	select @job_id=@id
	
	if @cmd = 'list'
	begin
	    if @vc_conv = 0
	    begin
		select job_id=jcmd_job_id, job_name=job_name, jcmd_seqno=jcmd_seqno,
			jcmd_text=substring(jcmd_text, 1, isnull(char_length(jcmd_text),1)-1)
		from sybmgmtdb..js_commands, sybmgmtdb..js_jobs
			where jcmd_job_id=@job_id and jcmd_job_id = job_id
			order by jcmd_seqno
		select @err=@@error, @rows=@@rowcount
	    end
	    else
	    begin
		select job_id=jcmd_job_id, job_name=convert(varchar(64), job_name), jcmd_seqno=jcmd_seqno,
			jcmd_text=convert(varchar(1800), substring(jcmd_text, 1, isnull(char_length(jcmd_text),1)-1))
		from sybmgmtdb..js_commands, sybmgmtdb..js_jobs
			where jcmd_job_id=@job_id and jcmd_job_id = job_id
			order by jcmd_seqno
		select @err=@@error, @rows=@@rowcount
	    end
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_commands', @err
			return -@@error
		end
		return 0
	end
	--
	-- js_client_role can only list the job text
	--
	if @is_admin = 0 and proc_role('js_user_role') = 0
	begin
		-- 19084 "Procedure %1!, you do not have permission to modify information for the specified scheduled job, job, schedule or running job."
		raiserror 19084, @sp_name
		return -@@error
	end
	--
	-- update lock the job
	--
	begin tran sp_sjobcmd
	save tran nested_tran
	update sybmgmtdb..js_jobs set job_update=@@spid where job_id = @job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_jobs', @err
		return -@@error
	end
	if @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19050 "Procedure %1!, parameter %2!, the specified job does not exist."
		select @vcname=@name
		raiserror 19050, @sp_name, @vcname
		return -@@error
	end
	select @owner=job_owner from sybmgmtdb..js_jobs where job_id=@job_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_jobs', @err
		return -@@error
	end
	--
	-- Must own the job, callers with js_admin_role are not allowed to
	-- modify the text of jobs they do not own.
	--
	if @owner != suser_name()
	begin
		rollback tran nested_tran
		commit tran
		-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
		raiserror 19084, @sp_name 
		return -@@error
	end

	if @cmd = 'add'
	begin

		select @seqno=max(jcmd_seqno) from sybmgmtdb..js_commands where jcmd_job_id = @job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_commands', @err
			return -@@error
		end
		if @seqno is NULL
			select @seqno=0
		else
			select @seqno=@seqno+1
		select @curpos=1, @len=isnull(char_length(@text), 0)
		while @curpos <= @len
		begin
			select @chunk=substring(@text, @curpos, 900) + char(10)
			insert sybmgmtdb..js_commands (jcmd_job_id, jcmd_type, jcmd_seqno, jcmd_text)
				values (@job_id, 0, @seqno, @chunk)
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
				raiserror 19075, @sp_name, 'js_commands', @err
				return -@@error
			end
			select @seqno=@seqno+1, @curpos=@curpos + 900
		end
		--
		-- release the update lock
		--
		update sybmgmtdb..js_jobs set job_update=0 where job_id = @job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
	end
	if @cmd = 'drop'
	begin
		delete sybmgmtdb..js_commands where jcmd_job_id = @job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
			raiserror 19073, @sp_name, 'js_commands', @err
			return -@@error
		end
	end
	commit tran
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobcmd')
begin
	print 'Created sp_sjobcmd'
	grant execute on sp_sjobcmd to js_user_role
	grant execute on sp_sjobcmd to js_client_role
	grant execute on sp_sjobcmd to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_sjobcopy')
	drop proc sp_sjobcopy
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobcopy  @name univarchar(),  @option univarchar()
--
--      @name is the name or id of a scheduled job, job or schedule.
--      The selection is made by using a prefix of sjname=, =jname or sname=.
--      With no prefix the default is the name or id of a scheduled job.
--      Example:-
--              'sjname=scheduled_job_name'
--              'jname=job_name'
--
--      @option is a list of name value pairs. Currently one option 'newname'
--	is defined, which is the name of the new scheduled job, job or schedule.
--	Example:-
--		sp_sjobcopy 'jname=orders_report', 'newname=waiting_orders_report'
--
create proc sp_sjobcopy (
	@name		univarchar(128),
	@option		univarchar(512)	= NULL
)
as
begin
	declare @opt_val_pair univarchar(512), @opt_name univarchar(512), @opt_value univarchar(512)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int, @is_admin int
	declare @err int, @rows int, @msgno int, @job_id int, @sjob_id int, @sched_id int, @id int
	declare @create_sjob int, @create_job int, @create_sched int
	--
	-- current values
	--
	declare @cur_enable int, @cur_server varchar(30), @cur_timeout int, @cur_locale varchar(30)
	declare @cur_job_id int, @cur_sched_id int, @cur_properties int, @cur_uproperties varchar(128)
	-- current job values
	declare @cur_desc univarchar(128), @cur_tmpl_id int
	declare @jcmd_text univarchar(901), @jcmd_type int, @seqno int, @max_seqno int
	-- current schedule values
	declare @cur_repeats int, @cur_units char(1), @cur_urepeats varchar(32)
	declare @cur_startdate datetime, @cur_starttime datetime, @cur_enddate datetime, @cur_endtime datetime
	declare @cur_days smallint, @cur_dates int, @cur_udays varchar(128), @cur_udates varchar(128), @cur_expired int
	--
	declare @owner varchar(30), @properties int, @newname univarchar(64)
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobcopy'

	select @is_admin=proc_role('js_admin_role')
	--
	-- Get and validate the name or id of the scheduled job or job.
	--
	select @opt_val_pair = ltrim(rtrim(@name))
	select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)

	if @eq_pos <= 0			-- no prefix, defaults to scheduled job
		select @opt_name='sjname', @opt_value=@opt_val_pair
	else if @eq_pos = @opt_val_len	-- name=  error
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	else
	begin
		select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
		select @opt_name=ltrim(rtrim(@opt_name))
		select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
		select @opt_value = ltrim(rtrim(@opt_value))
	end

	if @opt_name = 'sjname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
		select @create_sjob=1
	end
	else if @opt_name = 'jname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
		select @create_job=1
	end
	else if @opt_name = 'sname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sched', @return_id=1, @is_admin=@is_admin
		select @create_sched=1
	end
	else
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	if @id < 0 
	begin
		select @msgno = abs(@id)
		raiserror @msgno, @sp_name, '@name'
		return -@@error
	end

	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @option=ltrim(rtrim(@option))
	select @len=isnull(char_length(@option), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @option)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @option=stuff(@option, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @option=stuff(@option, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@option, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			select @opt_name = ltrim(rtrim(@opt_val_pair))
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		--
		if      @opt_name = 'newname'	select @newname=@opt_value
		else if @opt_name = 'sp_name'	select @sp_name=@opt_value
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
                	select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end
		select @curpos=@end_pos + 1
	end

	if @create_sjob = 1
	begin
		select @owner=sjob_owner, @properties=sjob_properties from sybmgmtdb..js_scheduledjobs where sjob_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
	end
	else if @create_job = 1
	begin
		select @owner=job_owner, @properties=job_properties from sybmgmtdb..js_jobs where job_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_jobs', @err
			return -@@error
		end
	end
	else
	begin
		select @owner=sched_owner, @properties=sched_properties from sybmgmtdb..js_schedules where sched_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_schedules', @err
			return -@@error
		end
	end
	--
	-- Must be js_admin_role or own the job or shared
	--
	if @is_admin = 0 and @owner != suser_name() and (@properties & (64+32)) = 0
	begin
		-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
		raiserror 19083, @sp_name, @id
		return -@@error
	end
	--
	-- Generate a key for the scheduled job, job or schedule
	--
	select @msgno=0
	if @create_sched = 1
	begin
		exec @sched_id=sp_js_getkey 'sched_id'
		if @sched_id < 0
			select @msgno=abs(@sched_id), @owner='sched_id'
	end
	else if @create_job = 1
	begin
		exec @job_id=sp_js_getkey 'job_id'
		if @job_id < 0
			select @msgno=abs(@job_id), @owner='job_id'
	end
	else
	begin
		exec @sjob_id=sp_js_getkey 'sjob_id'
		if @sjob_id < 0
			select @msgno=abs(@sjob_id), @owner='sjob_id'
	end
	if @msgno != 0
	begin
		raiserror @msgno, @sp_name, @owner
		return -@@error
	end

	-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
	-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
	-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
	-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
	-- 19050 "Procedure %1!, parameter %2!, the specified job does not exist."
	-- 19051 "Procedure %1!, parameter %2!, the specified schedule does not exist."
	-- 19052 "Procedure %1!, parameter %2!, the specified scheduled job does not exist."
	if @create_sjob = 1
	begin
		begin tran sp_sjobcopysjob
		save tran nested_tran
		--
		-- update lock the sjob
		--
		update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid where sjob_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sjob_id', @sjob_id
			if @err != 0
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
			else
			begin
				select @vcname=@name
				raiserror 19052, @sp_name, @vcname
			end
			return -@@error
		end
		--
		-- get the current values
		--
		select @cur_properties=sjob_properties, @cur_uproperties=sjob_uproperties,
			@cur_enable=sjob_enable, @cur_server=sjob_server, @owner=sjob_owner,
			@cur_locale=sjob_locale, @cur_timeout=sjob_timeout_value,
			@cur_job_id=sjob_job_id, @cur_sched_id=sjob_sched_id
		from sybmgmtdb..js_scheduledjobs where sjob_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows = 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sjob_id', @sjob_id
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		if @is_admin = 0 and @owner != suser_name() and (@cur_properties & 64) = 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sjob_id', @sjob_id
			raiserror 19083, @sp_name , @id
			return -@@error
		end

		insert sybmgmtdb..js_scheduledjobs
			(sjob_id, sjob_job_id, sjob_sched_id, sjob_update, sjob_enable, sjob_properties,
				sjob_created, sjob_timeout_value, sjob_owner, sjob_server,
				sjob_locale, sjob_name, sjob_uproperties)
		values (@sjob_id, @cur_job_id, @cur_sched_id, 0, @cur_enable, @cur_properties,
				getdate(), @cur_timeout, suser_name(), @cur_server,
				@cur_locale, @newname, @cur_uproperties)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sjob_id', @sjob_id
			raiserror 19075, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		--
		-- unlock the sjob
		--
		update sybmgmtdb..js_scheduledjobs set sjob_update=0 where sjob_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sjob_id', @sjob_id
			raiserror 19074, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		commit tran
		return @sjob_id
	end
	if @create_job = 1
	begin
		begin tran sp_sjobcopyjob
		save tran nested_tran
		--
		-- update lock the job
		--
		update sybmgmtdb..js_jobs set job_update=@@spid where job_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'job_id', @job_id
			if @err != 0
				raiserror 19074, @sp_name, 'js_jobs', @err
			else
			begin
				select @vcname=@name
				raiserror 19050, @sp_name, @vcname
			end
			return -@@error
		end
		--
		-- get the current values
		--
		select @cur_desc=job_description, @owner=job_owner,
			@cur_properties=job_properties, @cur_uproperties=job_uproperties,
			@cur_tmpl_id=job_tmpl_id, @cur_timeout=job_default_timeout
		from sybmgmtdb..js_jobs where job_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows = 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'job_id', @job_id
			raiserror 19076, @sp_name, 'js_jobs', @err
			return -@@error
		end
		if @is_admin = 0 and @owner != suser_name() and (@cur_properties & 32) = 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'job_id', @job_id
			raiserror 19083, @sp_name, @id
			return -@@error
		end
		--
		--
		insert sybmgmtdb..js_jobs
			(job_id, job_update, job_type, job_properties, job_owner, job_created,
			job_default_timeout, job_tmpl_id, job_name, job_description, job_uproperties)
		values (@job_id, 0, 0, @cur_properties, suser_name(), getdate(),
			@cur_timeout, @cur_tmpl_id, @newname, @cur_desc, @cur_uproperties)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'job_id', @job_id
			raiserror 19075, @sp_name, 'js_jobs', @err
			return -@@error
		end
		--
		-- create rows in the js_commands table
		--
		select @seqno=0
		select @max_seqno=max(jcmd_seqno), @jcmd_type=jcmd_type
			from sybmgmtdb..js_commands where jcmd_job_id = @id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			raiserror 19076, @sp_name, 'js_commands', @err
			return -@@error
		end
		select @max_seqno=isnull(@max_seqno, 0)
		
		while @seqno <= @max_seqno
		begin
			select @jcmd_text=jcmd_text from sybmgmtdb..js_commands
				where jcmd_job_id = @id and jcmd_seqno=@seqno
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				raiserror 19076, @sp_name, 'js_commands', @err
				return -@@error
			end

			insert sybmgmtdb..js_commands (jcmd_job_id, jcmd_type, jcmd_seqno, jcmd_text)
				values (@job_id, @jcmd_type, @seqno, @jcmd_text)
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				exec sp_js_putkey 'job_id', @job_id
				raiserror 19075, @sp_name, 'js_commands', @err
				return -@@error
			end
			select @seqno=@seqno + 1
		end

		-- unlock the job
		update sybmgmtdb..js_jobs set job_update=0 where job_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'job_id', @job_id
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
		commit tran
		return @job_id
	end

	if @create_sched = 1
	begin
		begin tran sp_sjobcopyschedule
		save tran nested_tran
		--
		-- update lock the schedule
		--
		update sybmgmtdb..js_schedules set sched_update=@@spid where sched_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sched_id', @sched_id
			if @err != 0
				raiserror 19074, @sp_name, 'js_schedules', @err
			else
			begin
				select @vcname=@name
				raiserror 19051, @sp_name, @vcname
			end
			return -@@error
		end
		--
		-- get current values
		--
		select  @cur_desc=sched_description, @owner=sched_owner,
			@cur_properties=sched_properties, @cur_uproperties=sched_uproperties,
			@cur_repeats=sched_interval,	@cur_units=sched_interval_units,
			@cur_startdate=sched_startdate,	@cur_starttime=sched_starttime,
			@cur_enddate=sched_enddate,	@cur_endtime=sched_endtime, 
			@cur_days=sched_days,		@cur_dates=sched_dates,
			@cur_udays=sched_udays,		@cur_udates=sched_udates,
			@cur_urepeats=sched_uinterval,	@cur_expired=sched_expired
		from sybmgmtdb..js_schedules where sched_id = @id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows = 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sched_id', @sched_id
			raiserror 19076, @sp_name, 'js_schedules', @err
			return -@@error
		end
		if @is_admin = 0 and @owner != suser_name() and (@cur_properties & 32) = 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sched_id', @sched_id
			raiserror 19083, @sp_name, @id
			return -@@error
		end
		--
		-- copy it
		--
		insert sybmgmtdb..js_schedules
			(sched_id, sched_update, sched_type, sched_properties, sched_owner, sched_created,
			sched_interval, sched_interval_units,
			sched_startdate, sched_starttime, sched_enddate, sched_endtime,
			sched_days, sched_dates, sched_name, sched_description, 
			sched_uproperties, sched_uinterval, sched_udays, sched_udates, sched_expired)
		values (@sched_id, 0, 0, @cur_properties, suser_name(), getdate(),
			@cur_repeats, @cur_units,
			@cur_startdate, @cur_starttime, @cur_enddate, @cur_endtime,
			@cur_days, @cur_dates, @newname, @cur_desc,
			@cur_uproperties, @cur_urepeats, @cur_udays, @cur_udates, @cur_expired)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sched_id', @sched_id
			raiserror 19075, @sp_name, 'js_schedules', @err
			return -@@error
		end
		--
		-- unlock the schedule
		--
		update sybmgmtdb..js_schedules set sched_update=0 where sched_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			exec sp_js_putkey 'sched_id', @sched_id
			raiserror 19074, @sp_name, 'js_schedules', @err
			return -@@error
		end
		commit tran
		return @sched_id
	end

	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobcopy')
begin
	print 'Created sp_sjobcopy'
	grant execute on sp_sjobcopy to js_user_role
	grant execute on sp_sjobcopy to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_sjobcontrol')
	drop proc sp_sjobcontrol
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobcontrol  @name univarchar(),  @option univarchar()
--
--      @option is a list of control options to the procedure.
--
--      The name or id of a scheduled job, a job or a running job
--	can be supplied by using sjname=, jname= or runid=.
--	For example:
--              'sjname=scheduled_job_name_or_id'
--              'jname=job_name_or_id'
--              'runid=23678'
--
--	Valid options are:
--          'terminate', 'enable', 'disable', 'run_now', 'run_once'
--
create proc sp_sjobcontrol (
	@name		univarchar(128),
	@option		univarchar(512)	= NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(128), @opt_name univarchar(32), @opt_value univarchar(96)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int
	declare @err int, @rows int, @msgno int, @is_admin int, @job_id int, @run_id int, @sjob_id int, @id int
	declare @cmd varchar(32), @caller varchar(30), @owner varchar(30), @sjob_id2 int, @job_name univarchar(64)
	declare @sched_id int, @desc univarchar(128), @properties int, @admin_cmd int, @all_users int, @admin_arg int
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobcontrol'

	select @is_admin=proc_role('js_admin_role'), @caller=suser_name(), @admin_cmd=0, @all_users=0, @admin_arg=1
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @value=ltrim(rtrim(@option))
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0					-- @option=opt_name
		begin
			select @opt_name=ltrim(rtrim(@opt_val_pair))
			if @opt_name = 'stop_js_timeout'
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_val_pair
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @eq_pos = @opt_val_len			-- @property=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len - @eq_pos)
			select @opt_value=ltrim(rtrim(@opt_value))
		end

		if @opt_name = 'terminate'	select @cmd='terminate'
		else if @opt_name = 'enable'	select @cmd='enable'
		else if @opt_name = 'disable'	select @cmd='disable'
		else if @opt_name = 'run_now'	select @cmd='run_now'
		else if @opt_name = 'run_once'	select @cmd='run_once'
		else if @opt_name = 'start_js'	select @cmd='start_js', @admin_cmd=1
		else if @opt_name = 'stop_js'	select @cmd='abort_js', @admin_cmd=1
		else if @opt_name = 'stop_js_wait'	select @cmd='stop_js', @admin_cmd=1, @admin_arg=2
		else if @opt_name = 'stop_js_timeout'
		begin
			select @cmd='stop_js', @admin_cmd=1
			-- check that the value is a +ve integer
			exec @err=sp_js_check_id @name_id=@opt_value, @cmd=3
			if @err < 0
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				select @vcbuf1=@opt_name, @vcbuf2=@opt_value
				raiserror 19070, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			select @admin_arg=@err
		end
		else if @opt_name = 'wakeup_js'	select @cmd='wakeup', @admin_cmd=1, @admin_arg=0
		else if @opt_name = 'pause_js'	select @cmd='pause_js', @admin_cmd=1
		else if @opt_name = 'resume_js'	select @cmd='resume_js', @admin_cmd=1
		else if @opt_name = 'start jstask'	select @cmd='start jstask', @admin_cmd=1
		else if @opt_name = 'stop jstask'	select @cmd='stop jstask', @admin_cmd=1
		else if @opt_name = 'start jsagent'	select @cmd='start jsagent', @admin_cmd=1
		else if @opt_name = 'stop jsagent'	select @cmd='stop jsagent', @admin_cmd=1
		else if @opt_name = 'sp_name'		select @sp_name=@opt_value
		else if @opt_name = 'all_users'
		begin
			-- 19077 'Procedure %1!, only a user with the role js_admin_role can specify the owner or all_users.'
			if @is_admin = 0
			begin
				raiserror 19077, @sp_name
				return -@@error
			end
		end
		else
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		
		select @curpos=@end_pos + 1
	end
	--
	-- Job Scheduler Admin Commands
	--
	if @admin_cmd = 1
	begin
		if @is_admin = 0 and proc_role('sa_role') = 0
		begin
			-- 19084 'Procedure %1!, you do not have permission to modify information for the specified scheduled job, job, schedule or running job.'
			raiserror 19084, @sp_name
			return -@@error
		end
		exec @err=sp_js_wakeup @cmd, @admin_arg
                --CR 430862-1
                return @err
	end
	--
	-- Get and validate the name or id of the scheduled job, job or runid.
	-- 
	select @opt_val_pair = ltrim(rtrim(@name))
	select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)
	if @eq_pos <= 0				-- no prefix, defaults to scheduled job
		select @opt_name='sjname', @opt_value=@opt_val_pair
	else if @eq_pos = @opt_val_len		-- opt_name=  error
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	else
	begin
		select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
		select @opt_name=ltrim(rtrim(@opt_name))
		select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
		select @opt_value = ltrim(rtrim(@opt_value))
	end
	select @sjob_id=NULL, @job_id=NULL, @run_id=NULL
	if @opt_name = 'sjname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@all_users
		select @sjob_id=@id
		-- sp_sjobcontrol @name='js_task', @option=...
		if @id < 0 and @opt_value = 'js_task'
		begin
			select @id=0, @sjob_id=NULL
		end
	end
	else if @opt_name = 'jname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@all_users
		select @job_id=@id
	end
	else if @opt_name = 'runid'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='jsh', @return_id=1, @is_admin=@all_users
		select @run_id=@id
	end
	else
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	if @id < 0
	begin
		select @msgno = abs(@id)
		raiserror @msgno, @sp_name, '@name'
		return -@@error
	end
	-- get the job name to match in the js_history
	if @job_id is not NULL and @cmd = 'terminate'
	begin
		select @job_name=job_name from sybmgmtdb..js_jobs where job_id=@job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_jobs', @err
			return -@@error
		end
		if @rows < 1
		begin
			-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
			select @vcname=@name
			raiserror 19050, @sp_name, @vcname
			return -@@error
		end
	end

	if @cmd is NULL
		return 0

	--
	-- Handle the simple case, where we have a run_id for a single running job
	--
	if @run_id is not NULL
	begin
		--
		-- check caller has permission
		--
		select @owner=jsh_user_req from sybmgmtdb..js_history where jsh_exid=@run_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_history', @err
			return -@@error
		end
		if @rows != 1
		begin
			if @rows > 1
			begin
				-- 19086 'Procedure %1!, internal error duplicate rows with runid %2!, in table %3!.'
				raiserror 19086, @sp_name, @run_id, 'js_history'
				return -@@error
			end
			-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
			raiserror 19082, @sp_name, @run_id
			return 0
		end
		if @all_users = 0 and @caller != @owner
		begin
			-- 19084 'Procedure %1!, you do not have permission to modify information for the specified scheduled job, job, schedule or running job.'
			raiserror 19084, @sp_name
			return -@@error
		end
		if @cmd = 'terminate'
		begin
			exec sp_js_wakeup 'terminate_job', @run_id
			return 0
		end
		-- 19081 'Procedure %1!, the cmd %2! is not valid with a running job id.'
		raiserror 19081, @sp_name, @cmd
		return -@@error
	end
	--
	--
	--
	if @cmd = 'terminate'
	begin
		-- consider select into #temptable and then process
		if @sjob_id is not NULL
			declare stop_jobs cursor for select jsh_exid from sybmgmtdb..js_history
				where jsh_sjobid=@sjob_id and (jsh_state like '[QR]%' or jsh_state like '[CTX]1')
					and (@all_users = 1 or jsh_user_req = @caller)
				for read only
		else
			declare stop_jobs cursor for select jsh_exid from sybmgmtdb..js_history
				where jsh_jobname=@job_name and (jsh_state like '[QR]%' or jsh_state like '[CTX]1')
					and (@all_users = 1 or jsh_user_req = @caller)
				for read only
		open stop_jobs
		fetch stop_jobs into @sjob_id2
		while @@sqlstatus = 0
		begin
			-- inform the ASE task
			exec sp_js_wakeup 'terminate_job', @sjob_id2
			fetch stop_jobs into @sjob_id2
		end
		close stop_jobs
		deallocate cursor stop_jobs
		return 0
	end
	--
	--
	--
	if @cmd = 'enable' or @cmd = 'disable'
	begin
		-- 19068 'Procedure %1!, failed to enable scheduled job, update error %2!.'
		-- 19069 'Procedure %1!, failed to disable scheduled job, update error %2!.'
		if @cmd = 'disable'	select @id=0,@msgno=19069
		else	select @id=1,@msgno=19068
		--
		-- enable  all scheduled jobs using this job_name and owned by the caller
		-- disable all scheduled jobs using this job_name and owned by the caller or 'all_users'
		--
		if @job_id is not NULL
		begin
			update sybmgmtdb..js_scheduledjobs set sjob_enable=@id where sjob_job_id=@job_id
				and ( sjob_owner = @caller or (@cmd = 'disable' and @all_users = 1) )
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				raiserror @msgno, @sp_name, @err
				return -@@error
			end
			if @rows <= 0
				return 0
			declare sjob_enable cursor for select sjob_id sjob_enable from sybmgmtdb..js_scheduledjobs
				where sjob_job_id=@job_id and
					( sjob_owner = @caller or (@cmd = 'disable' and @all_users=1) )
				for read only
			open sjob_enable
			fetch sjob_enable into @sjob_id2, @id
			while @@sqlstatus = 0
			begin
				--
				-- inform the ASE task
				--
				if @id = 0
					exec sp_js_wakeup 'job_disabled', @sjob_id2
				else
					exec sp_js_wakeup 'job_enabled', @sjob_id2
			end
			close sjob_enable
			deallocate cursor sjob_enable
			return 0
		end
		--
		-- enable/disable a single scheduled job
		--
		if @cmd = 'enable'
		begin
			select @owner=sjob_owner from sybmgmtdb..js_scheduledjobs where sjob_id=@sjob_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
			if @rows <= 0
			begin
				-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
				select @vcname=@name
				raiserror 19050, @sp_name, @vcname
				return 0
			end
			if @owner != suser_name()
			begin
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name 
				return -@@error
			end
		end

		update sybmgmtdb..js_scheduledjobs set sjob_enable=@id where sjob_id = @sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19068 'Procedure %1!, failed to enable scheduled job, update error %2!.'
			-- 19069 'Procedure %1!, failed to disable scheduled job, update error %2!.'
			raiserror @msgno, @sp_name, @err
			return -@@error
		end
		if @rows <= 0
		begin
			-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
			select @vcname=@name
			raiserror 19050, @sp_name, @vcname
			return 0
		end
		--
		-- inform the ASE task
		--
		if @cmd = 'disable'
			exec sp_js_wakeup 'job_disabled', @sjob_id
		else
			exec sp_js_wakeup 'job_enabled', @sjob_id
		return 0
	end

	if @cmd = 'run_now'
	begin
		if @job_id is not NULL
		begin
			--
			-- We were given a job name, lookup a scheduled job using it
			--
			select @sjob_id=sjob_id, @id=sjob_enable, @properties=sjob_properties, @owner=sjob_owner
				from sybmgmtdb..js_scheduledjobs
				where sjob_job_id=@job_id and sjob_owner = @caller
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
			--
			-- Check if there is a shared scheduled job we can use
			--
			if @rows = 0
			begin
				select @sjob_id=sjob_id, @id=sjob_enable, @properties=sjob_properties, @owner=sjob_owner
					from sybmgmtdb..js_scheduledjobs
					where sjob_job_id=@job_id and (sjob_properties & 64) = 64
				select @err=@@error, @rows=@@rowcount
				if @err != 0
				begin
					raiserror 19076, @sp_name, 'js_scheduledjobs', @err
					return -@@error
				end
			end
			--
			-- There must be only one scheduled job, otherwise we might pick the wrong one (server)
			--
			if @rows > 1	
			begin
				-- 19097 "Procedure %1!, %2! is a non-unique name for a scheduledjob, job or schedule, the id value must be used."
				-- 19071 "Procedure %1!, parameter %2!, more than one scheduled job exists with that name."
				select @vcname=@name
				raiserror 19071, @sp_name, @vcname
				return -@@error
			end
		end
		else
		begin
			select @id=sjob_enable, @properties=sjob_properties, @owner=sjob_owner
				from sybmgmtdb..js_scheduledjobs where sjob_id=@sjob_id and sjob_owner=@caller
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
			--
			-- Check if there is a shared scheduled job we can use
			-- There must be only one, otherwise we might pick the wrong one (server)
			-- but the lookup of the sjob_name already handled this.
			--
			if @rows = 0
			begin
				select @sjob_id=sjob_id, @id=sjob_enable, @properties=sjob_properties, @owner=sjob_owner
					from sybmgmtdb..js_scheduledjobs
					where sjob_id=@sjob_id and (sjob_properties & 64) = 64
				select @err=@@error, @rows=@@rowcount
				if @err != 0
				begin
					raiserror 19076, @sp_name, 'js_scheduledjobs', @err
					return -@@error
				end
			end
			if @rows = 0 select @sjob_id = NULL
		end
		if @sjob_id is NULL
		begin
			-- 19052 'Procedure %1!, parameter %2!, the specified scheduled job does not exist.'
			select @vcname=@name
			raiserror 19052, @sp_name, @vcname
			return -@@error
		end
		if @id = 0	-- the scheduled job is disabled
		begin
			-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
			raiserror 19083, @sp_name, @job_id
			return -@@error
		end
		if @properties & 128 = 128
			exec sp_js_wakeup 'run_once', @sjob_id
		else	exec sp_js_wakeup 'run_now', @sjob_id
		return 0
	end
	--
	--
	--
	if @cmd = 'run_once'
	begin
		select @id=sjob_enable, @owner=sjob_owner, @properties=sjob_properties
			from sybmgmtdb..js_scheduledjobs where sjob_id=@sjob_id and sjob_owner = @caller
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		if @rows = 0
		begin
			select @id=sjob_enable, @properties=sjob_properties, @owner=sjob_owner
				from sybmgmtdb..js_scheduledjobs
			where sjob_id=@sjob_id and (sjob_properties & 64) = 64
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				raiserror 19076, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
		if @rows = 0
		begin
			-- 19052 'Procedure %1!, parameter %2!, the specified scheduled job does not exist.'
			select @vcname=@name
			raiserror 19052, @sp_name, @vcname
			return -@@error
		end
		--
		-- There must be only one scheduled job, otherwise we might pick the wrong one (server)
		--
		if @rows > 1	
		begin
			-- 19071 "Procedure %1!, parameter %2!, more than one scheduled job exists with that name."
			select @vcname=@name
			raiserror 19071, @sp_name, @vcname
			return -@@error
		end
		if @id = 0	-- the scheduled job is disabled
		begin
			-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
			raiserror 19083, @sp_name, @job_id
			return -@@error
		end
		-- schedule to run at its next starttime
		exec sp_js_wakeup 'run_once', @sjob_id
		return 0
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobcontrol')
begin
	print 'Created sp_sjobcontrol'
	grant execute on sp_sjobcontrol to js_client_role
	grant execute on sp_sjobcontrol to js_user_role
	grant execute on sp_sjobcontrol to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_sjobsetstatus')
	drop proc sp_sjobsetstatus
go
--
-- Internal JobScheduler stored procedure (JS Agent)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_sjobsetstatus (
	@name		univarchar(64),
	@option		univarchar(512) = NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(512), @opt_name univarchar(32), @opt_value univarchar(255)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(64)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int
	declare @err int, @rows int, @msgno int, @is_admin int, @run_id int
	declare @exit_code int, @user_code int, @os_code int, @atat_error int, @smsg univarchar(64), @lmsg univarchar(255)
	declare @sp_name varchar(32), @trun_id varchar(64), @user_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobsetstatus'

	select @trun_id = ltrim(rtrim(@name)), @is_admin=proc_role('js_admin_role')
	exec @run_id=sp_js_check_id @name_id=@trun_id, @cmd=1, @table='jsh', @is_admin=@is_admin
	if @run_id < 0
	begin
		select @msgno = abs(@run_id)
		raiserror @msgno, @sp_name, '@name'
		return -@@error
	end
	--
	-- check caller has permission
	--
	select @user_name=jsh_user_run, @exit_code=jsh_exit_code,
		@user_code=jsh_user_code, @os_code=jsh_os_code,
		@atat_error=jsh_atat_error, @smsg=jsh_smsg, @lmsg=jsh_lmsg
	from sybmgmtdb..js_history where jsh_exid=@run_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_history', @err
		return -@@error
	end
	if @rows != 1
	begin
		if @rows > 1
		begin
			-- 19086 'Procedure %1!, internal error duplicate rows with runid %2!, in table %3!.'
			raiserror 19086, @sp_name, @run_id, 'js_history'
			return -@@error
		end
		-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
		raiserror 19082, @sp_name, @run_id
		return -@@error
	end
	if proc_role('js_admin_role') = 0 and @user_name != suser_name()
	begin
		-- 19084 'Procedure %1!, you do not have permission to modify information for the specified scheduled job, job, schedule or running job.'
		raiserror 19084, @sp_name
		return -@@error
	end

	select @value=ltrim(rtrim(@option))
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0					-- @option=opt_name
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else if @eq_pos = @opt_val_len			-- @property=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end

		if @opt_name = 'exit_code'
		begin
			-- check that the value is a +ve integer
			exec @exit_code=sp_js_check_id @name_id=@opt_value, @cmd=3
			if @exit_code < 0 or @exit_code > 4
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, 'exit_code', @exit_code
				return -@@error
			end
		end
		else if @opt_name = 'user_code'
		begin
			select @user_code=convert(int, @opt_value)
		end
		else if @opt_name = 'os_code'
		begin
			select @os_code=convert(int, @opt_value)
		end
		else if @opt_name = 'atat_error'
		begin
			select @atat_error=convert(int, @opt_value)
		end
		else if @opt_name = 'shortmsg'
		begin
			select @smsg=@opt_value
		end
		else if @opt_name = 'longmsg'
		begin
			select @lmsg=@opt_value
		end
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
			select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end
		select @curpos=@end_pos + 1
	end
	update sybmgmtdb..js_history set jsh_exit_code=@exit_code, jsh_user_code=@user_code,
		jsh_os_code=@os_code, jsh_atat_error=@atat_error,
		jsh_smsg=@smsg, jsh_lmsg=@lmsg where jsh_exid=@run_id
	select @err=@@error

	if @err != 0
	begin
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_history', @err
		return -@@error
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobsetstatus')
begin
	print 'Created sp_sjobsetstatus'
	grant execute on sp_sjobsetstatus to js_user_role
	grant execute on sp_sjobsetstatus to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_sjobdrop')
	drop proc sp_sjobdrop
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobdrop  @name univarchar(),  @option univarchar()
--
--      @name is the name or id of a scheduled job, a job or a schedule to
--      be dropped.
--      The selection is made by using a prefix of sjname=, jname= or sname=.
--      With no prefix the default is the name or id of a scheduled job.
--      Example:-
--              'sjname=scheduled_job_name_or_id'
--              'jname=job_name_or_id'
--              'sname=schedule_name_or_id'
--
--      @option is a list of control options to the procedure, valid options
--      are 'show', 'force', 'all' and 'all_users'.
--
--      The 'show' option displays the scheduled jobs, jobs and schedules that
--      would have been dropped, had the 'show' option not been supplied.
--	The 'force' option does not check for running jobs.
--      The 'all_users' option is only available to callers with the role js_admin_role.
--
create proc sp_sjobdrop (
	@name		univarchar(128),
	@option		univarchar(512) = NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(128), @opt_name univarchar(32), @opt_value univarchar(96)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128), @vc_conv int
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @sp_name varchar(32), @tell_ase int, @owner varchar(30)
	declare @err int, @rows int, @msgno int, @is_admin int, @sjob_count int, @id int, @force int
	declare @sjob_id int, @job_id int, @sched_id int, @all int, @all_users int, @show int
	-- 
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobdrop'
	select  @tell_ase=0, @all=0, @all_users=0, @show=0, @force=0, @vc_conv=1
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @value=ltrim(rtrim(@option))
	select @len=isnull(char_length(@value), 0), @curpos=1
	
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos - @curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			select @opt_val_pair=ltrim(rtrim(@opt_val_pair))
			if @opt_val_pair = 'all' or @opt_val_pair = 'all_users'
				or @opt_val_pair = 'show' or @opt_val_pair = 'force'
			begin
				select @opt_name=@opt_val_pair
			end
			else
			begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_val_pair
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		if @opt_name = 'show'		select @show=1
		else if @opt_name = 'sp_name'	select @sp_name=@opt_value
		else if @opt_name = 'force'	select @force=1
		else if @opt_name = 'all'	select @all=1
		else if @opt_name = 'all_users'
		begin
			-- 19077 'Procedure %1!, only a user with the role js_admin_role can specify the owner or all_users.'
			if @is_admin = 0
			begin
				raiserror 19077, @sp_name
				return -@@error
			end
			select @all_users=1
		end
		else if @opt_name = 'varchar' or @opt_name = 'ascii'	select @vc_conv=1
		else if @opt_name = 'unichar' or @opt_name = 'utf8'	select @vc_conv=0
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
                	select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end
		select @curpos=@end_pos + 1
	end
	--
	-- Get and validate the name or id of the scheduled job, job or schedule.
	--
	select @opt_val_pair = ltrim(rtrim(@name))
	select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)
	if @eq_pos <= 0				-- no prefix, defaults to scheduled job
		select @opt_name='sjname', @opt_value=@opt_val_pair
	else if @eq_pos = @opt_val_len		-- opt_name=  error
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	else
	begin
		select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
		select @opt_name=ltrim(rtrim(@opt_name))
		select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
		select @opt_value = ltrim(rtrim(@opt_value))
	end
	select @sjob_id=NULL, @job_id=NULL, @sched_id=NULL
	if @opt_name = 'sjname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@all_users
		if @id >= 0
		begin
			select @job_id=sjob_job_id, @sched_id=sjob_sched_id from sybmgmtdb..js_scheduledjobs
				where sjob_id=@id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_schedules', @err
				return -@@error
			end
			if @rows <= 0
			begin
				-- 19052 "Procedure %1!, parameter %2!, the specified scheduled job does not exist."
				select @vcname=@name
				raiserror 19052, @sp_name, @vcname
				return -@@error
			end
		end
		select @sjob_id=@id
	end
	else if @opt_name = 'jname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@all_users
		select @job_id=@id
	end
	else if @opt_name = 'sname'
	begin
		exec @id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sched', @return_id=1, @is_admin=@all_users
		select @sched_id=@id
	end
	else
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                select @vcbuf1=@opt_val_pair
		raiserror 19098, @sp_name, @vcbuf1
		return -@@error
	end
	if @id < 0
	begin
		select @msgno = abs(@id), @vcname=@name
		raiserror @msgno, @sp_name, @vcname
		return -@@error
	end
	
	-- the logic for a scheduled job is:
	-- all
	-- 	update lock the schedule, then job
	-- update lock the sjob
	--
	-- if @is_admin 0 or @all_users = 0
	-- 	check sjob owner
	-- 	if @all = 1
	-- 		if @is_admin 0  check job and schedule owner
	-- 		check any other sj refs to job, sched
	-- check sjob running
	--
	-- if @all = 0
	-- 	delete sj
	-- 	return
	--
	-- delete sj
	-- if no refs delete sched
	--     else release lock
	-- if no refs delete cmd, job
	--     else release lock
	-- return
	--
	-- set sjob, job and sched ids for a sjob, so we must check sjob is not NULL first.
	select @owner=suser_name()
	if @sjob_id is not NULL
	begin
		-- all or all_users
		-- 	update lock the schedule, then job
		-- update lock the sjob
		--
		begin tran sp_sjobdrop1
		save  tran nested_tran
		if @all = 1
		begin
			update sybmgmtdb..js_schedules set sched_update=@@spid where sched_id=@sched_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0 or @rows != 1
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_schedules', @err
				return -@@error
			end
			update sybmgmtdb..js_jobs set job_update=@@spid where job_id=@job_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0 or @rows != 1
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_jobs', @err
				return -@@error
			end
		end
		update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		--
		-- In the time between reading the job_id and sched_id from the scheduled job and update locking
		-- the scheduled job, it is theoretically possible for the scheduled job to have been droppped
		-- and re-created using a different job and schedule. We cannot reverse the locking order to
		-- prevent this as that would lead to deadlocks and race conditions. We could re-read the job_id
		-- and sched_id after locking the scheduled job, however the way ids are generated makes it
		-- near impossible for the re-created scheduled job to have the same id, so it is not necessary.
		--
		-- if @is_admin 0 or @all_users 0
		-- 	check sjob owner
		-- if @all = 1
		-- 	check job and schedule owner
		--
		if @is_admin = 0 or @all_users = 0
		begin
			if not exists (select sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_id = @sjob_id and sjob_owner = @owner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name
				return -@@error
			end
		end
		if @all = 1
		begin
			--
			-- Check the owner of the job and schedule
			--
			if @all_users = 0 and exists (select job_id from sybmgmtdb..js_jobs
				where job_id = @job_id and job_owner != @owner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name
				return -@@error
			end
			if @all_users = 0 and exists (select sched_id from sybmgmtdb..js_schedules
				where sched_id = @sched_id and sched_owner != @owner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name
				return -@@error
			end
			--
			-- other scheduled jobs using them
			--
			if exists (select sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_id != @sjob_id and ( sjob_sched_id = @sched_id or sjob_job_id = @job_id ))
			begin
				rollback tran nested_tran
				commit tran
				-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
				select @opt_val_pair='the job or schedule used by ' + @name + '.'
                		select @vcbuf1=@opt_val_pair
				raiserror 19079, @sp_name, @vcbuf1
				return -@@error
			end
		end
		--
		-- check sjob running
		--
		if @show != 1 and @force != 1
		begin
			if exists (select jsh_sjobid from sybmgmtdb..js_history where
					( jsh_sjobid = @sjob_id) and
					( jsh_state like '[QR]%' or jsh_state like '[CTX]1' )
				  )
			begin
				rollback tran nested_tran
				commit tran
				-- 19072 'Procedure %1!, unable to perform the operation while running jobs are using %2!.'
				select @vcname=@name
				raiserror 19072, @sp_name, @vcname
				return -@@error
			end
		end
		--
		-- if @all = 0
		-- 	delete sj
		-- 	return
		--
		if @all = 0
		begin
			if @show = 1
			begin
			    if @vc_conv = 0
			    begin
				select 'sp_sjobdrop @name''' + @name + ''', @option''' + @option + ''' would drop scheduledjob:'
				select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=sjob_name
					from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
			    end
			    else
			    begin
				select 'sp_sjobdrop @name''' + convert(varchar(64), @name) + ''', @option''' + convert(varchar(512), @option) + ''' would drop scheduledjob:'
				select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=convert(varchar(64), sjob_name)
					from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
			    end
				rollback tran nested_tran
				commit tran
				return 0
			end
			delete from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
			select @err=@@error
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
				raiserror 19073, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
			commit tran
			exec sp_js_wakeup 'job_deleted', @sjob_id
			return 0
		end
		--
		-- delete sj
		-- if no refs delete sched
		--     else release lock
		-- if no refs delete cmd, job
		--     else release lock
		-- return
		if @show = 1
		begin
		    if @vc_conv = 0
		    begin
			select 'sp_sjobdrop @name''' + @name + ''', @option''' + @option + ''' would drop scheduledjob:'
			select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=sjob_name
				from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
		    end
		    else
		    begin
			select 'sp_sjobdrop @name''' + convert(varchar(64), @name) + ''', @option''' + convert(varchar(512), @option) + ''' would drop scheduledjob:'
			select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=convert(varchar(64), sjob_name)
				from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
		    end
		end
		else
		begin
			delete from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
			select @err=@@error
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
				raiserror 19073, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
		select @rows=count(sjob_job_id) from sybmgmtdb..js_scheduledjobs
			where sjob_job_id = @job_id and sjob_id != @sjob_id
		select @err=@@error
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		if @rows = 0
		begin
			if @show = 1
			begin
			    if @vc_conv = 0
			    begin
				select 'and job:'
				select job_id=job_id, job_name=job_name
					from sybmgmtdb..js_jobs where job_id = @job_id
			    end
			    else
			    begin
				select 'and job:'
				select job_id=job_id, job_name=convert(varchar(64), job_name)
					from sybmgmtdb..js_jobs where job_id = @job_id
			    end
			end
			else
			begin
				delete from sybmgmtdb..js_commands where jcmd_job_id = @job_id
				select @err=@@error
				if @err != 0
				begin
					rollback tran nested_tran
					commit tran
					-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
					raiserror 19073, @sp_name, 'js_commands', @err
					return -@@error
				end
				delete from sybmgmtdb..js_jobs where job_id = @job_id
				select @err=@@error
				if @err != 0
				begin
					rollback tran nested_tran
					commit tran
					-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
					raiserror 19073, @sp_name, 'js_jobs', @err
					return -@@error
				end
			end
		end
		else
		begin
			update sybmgmtdb..js_jobs set job_update=0 where job_id=@job_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0 or @rows != 1
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_jobs', @err
				return -@@error
			end
		end
		--
		select @rows=count(sjob_sched_id) from sybmgmtdb..js_scheduledjobs
			where sjob_sched_id = @sched_id and sjob_id != @sjob_id
		select @err=@@error
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		if @rows = 0
		begin
			if @show = 1
			begin
			    if @vc_conv = 0
			    begin
				select 'and schedule:'
				select sched_id=sched_id, sched_name=sched_name
					from sybmgmtdb..js_schedules where sched_id = @sched_id
			    end
			    else
			    begin
				select 'and schedule:'
				select sched_id=sched_id, sched_name=convert(varchar(64), sched_name)
					from sybmgmtdb..js_schedules where sched_id = @sched_id
			    end
			end
			else
			begin
				delete from sybmgmtdb..js_schedules where sched_id = @sched_id
				select @err=@@error
				if @err != 0
				begin
					rollback tran nested_tran
					commit tran
					-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
					raiserror 19073, @sp_name, 'js_schedules', @err
					return -@@error
				end
			end
		end
		else
		begin
			update sybmgmtdb..js_schedules set sched_update=0 where sched_id=@sched_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0 or @rows != 1
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_schedules', @err
				return -@@error
			end
		end
		if @show = 1
		begin
			rollback tran nested_tran
			commit tran
			return 0
		end
		commit tran
		exec sp_js_wakeup 'job_deleted', @sjob_id
		return 0
	end
	--
	-- the logic for a job (or schedule) is
	--	update lock the job
	--	if all or all_users update lock sj's referencing the job
	--	
	--	if @is_admin 0 or @all_users 0
	--		check job owner
	--	if @all = 1
	--		check all sj references are owned
	--
	--	if @all = 0 and @all_users = 0
	--		check no sj references
	--	else
	--		delete sj references owned (all) or any (all_users)
	--	delete cmd, job
	--	return
	--
	if @job_id is not NULL
	begin
		-- make a list of the scheduled jobs that may be deleted
		select @sjob_count=0
		select sjob_id into #sjobdrop_1 from sybmgmtdb..js_scheduledjobs where
			(sjob_job_id = @job_id) and (@all_users = 1 or sjob_owner = @owner)
		select @err=@@error, @sjob_count = @@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end

		begin tran sp_sjobdrop2
		save  tran nested_tran
		-- update lock the job
		update sybmgmtdb..js_jobs set job_update=@@spid where job_id=@job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
		-- if all or all_users update lock sj's referencing the job
		if @all = 1 or @all_users = 1
		begin
			update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid where sjob_job_id=@job_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
		--
		-- if @is_admin 0
		--	check job owner
		-- if @all = 1
		--	check all sj references are owned
		if @is_admin = 0 or @all_users = 0
		begin
			if not exists (select job_id from sybmgmtdb..js_jobs
				where job_id = @job_id and job_owner = @owner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name
				return -@@error
			end
		end
		if @all = 1
		begin
			if exists (select sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_job_id = @job_id and sjob_owner != @owner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
				select @vcname=@name
				raiserror 19079, @sp_name, @vcname
				return -@@error
			end
		end
		--
		-- if @all = 0 and @all_users = 0
		-- 	check no sj references
		-- else
		-- 	delete sj references owned (all) or any (all_users)
		-- delete cmd, job
		-- return
		--
		select @sjob_count=0
		if @all = 0 and @all_users = 0
		begin
			if exists (select sjob_id from sybmgmtdb..js_scheduledjobs where sjob_job_id = @job_id)
			begin
				rollback tran nested_tran
				commit tran
				-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
				select @vcname=@name
				raiserror 19079, @sp_name, @vcname
				return -@@error
			end
		end
		else
		begin
			if @show = 1
			begin
			    if @vc_conv = 0
			    begin
				select 'sp_sjobdrop @name''' + @name + ''', @option''' + @option + ''' would drop job:'
				select job_id=job_id, job_name=job_name
					from sybmgmtdb..js_jobs where job_id = @job_id

				select @rows=count(sjob_id) from sybmgmtdb..js_scheduledjobs
				where sjob_job_id = @job_id and (@all_users = 1 or sjob_owner = @owner)
				select @err=@@error
				if @err = 0 and @rows > 0
				begin
					select 'and scheduled jobs:'
					select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=sjob_name
					from sybmgmtdb..js_scheduledjobs where sjob_job_id = @job_id and
						(@all_users = 1 or sjob_owner = @owner)
				end
			    end
			    else
			    begin
				select 'sp_sjobdrop @name''' + convert(varchar(64), @name) + ''', @option''' + convert(varchar(512), @option) + ''' would drop job:'
				select job_id=job_id, job_name=convert(varchar(64), job_name)
					from sybmgmtdb..js_jobs where job_id = @job_id

				select @rows=count(sjob_id) from sybmgmtdb..js_scheduledjobs
				where sjob_job_id = @job_id and (@all_users = 1 or sjob_owner = @owner)
				select @err=@@error
				if @err = 0 and @rows > 0
				begin
					select 'and scheduled jobs:'
					select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=convert(varchar(64), sjob_name)
					from sybmgmtdb..js_scheduledjobs where sjob_job_id = @job_id and
						(@all_users = 1 or sjob_owner = @owner)
				end
			    end
				rollback tran nested_tran
				commit tran
				return 0
			end
			-- check running
			if @force = 1
				select @sjob_id=NULL
			else
				select @sjob_id=jsh_sjobid from sybmgmtdb..js_history where
					( jsh_state like '[QR]%' or jsh_state like '[CTX]1' ) and
					  jsh_sjobid in ( select sjob_id from sybmgmtdb..js_scheduledjobs where
							(sjob_job_id = @job_id       ) and
							(@all_users = 1 or sjob_owner = @owner) )
			if @sjob_id is not NULL
			begin
				rollback tran nested_tran
				commit tran
				-- 19072 'Procedure %1!, unable to perform the operation while running jobs are using %2!.'
				select @opt_val_pair='scheduled job id=' + convert(varchar(16), @sjob_id)
                		select @vcbuf1=@opt_val_pair
				raiserror 19072, @sp_name, @vcbuf1
				return -@@error
			end

			delete from sybmgmtdb..js_scheduledjobs where sjob_job_id = @job_id and
				(@all_users = 1 or sjob_owner = @owner)
			select @err=@@error
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
				raiserror 19073, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
			-- we update locked all sjobs using job, but may not have deleted them all
			update sybmgmtdb..js_scheduledjobs set sjob_update=0 where sjob_update=@@spid
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
		-- delete cmd, job
		-- return
		delete from sybmgmtdb..js_commands where jcmd_job_id = @job_id
		select @err=@@error
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
			raiserror 19073, @sp_name, 'js_commands', @err
			return -@@error
		end
		delete from sybmgmtdb..js_jobs where job_id = @job_id
		select @err=@@error
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
			raiserror 19073, @sp_name, 'js_jobs', @err
			return -@@error
		end
		commit tran
		-- tell ASE
		if @sjob_count is NULL or @sjob_count = 0
			return 0
		declare sjobdrop cursor for select sjob_id from #sjobdrop_1
			for read only
		open sjobdrop
		fetch sjobdrop into @sjob_id
		while @@sqlstatus = 0
		begin
			if not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id)
				exec sp_js_wakeup 'job_deleted', @sjob_id
			fetch sjobdrop into @sjob_id
		end
		close sjobdrop
		deallocate cursor sjobdrop
		return 0
	end

	if @sched_id is not NULL
	begin
		-- make a list of the scheduled jobs that may be deleted
		select @sjob_count=0
		select sjob_id into #sjobdrop_2 from sybmgmtdb..js_scheduledjobs where
			(sjob_sched_id = @sched_id) and (@all_users = 1 or sjob_owner = @owner)
		select @err=@@error, @sjob_count = @@rowcount
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		begin tran sp_sjobdrop3
		save  tran nested_tran
		-- update lock the schedule
		update sybmgmtdb..js_schedules set sched_update=@@spid where sched_id=@sched_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_schedules', @err
			return -@@error
		end
		-- if all or all_users update lock sj's referencing the schedule
		if @all = 1 or @all_users = 1
		begin
			update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid where sjob_sched_id=@sched_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
		--
		-- if @is_admin 0
		--	check schedule owner
		-- if @all = 1
		--	check all sj references are owned
		if @is_admin = 0 or @all_users = 0
		begin
			if not exists (select sched_id from sybmgmtdb..js_schedules
				where sched_id = @sched_id and sched_owner = @owner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name
				return -@@error
			end
		end
		if @all = 1
		begin
			if exists (select sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_sched_id = @sched_id and sjob_owner != @owner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
				select @vcname=@name
				raiserror 19079, @sp_name, @vcname
				return -@@error
			end
		end
		--
		-- if @all = 0 and @all_users = 0
		-- 	check no sj references
		-- else
		-- 	delete sj references owned (all) or any (all_users)
		-- delete schedule
		-- return
		--
		if @all = 0 and @all_users = 0
		begin
			if exists (select sjob_id from sybmgmtdb..js_scheduledjobs where sjob_sched_id = @sched_id)
			begin
				rollback tran nested_tran
				commit tran
				-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
				select @vcname=@name
				raiserror 19079, @sp_name, @vcname
				return -@@error
			end
		end
		else
		begin
			if @show = 1
			begin
			    if @vc_conv = 0
			    begin
				select 'sp_sjobdrop @name=''' + @name + ''', @option=''' + @option + ''' would drop schedule:'
				select sched_id=sched_id, sched_name=sched_name
					from sybmgmtdb..js_schedules where sched_id = @sched_id

				select @rows=count(sjob_id) from sybmgmtdb..js_scheduledjobs
				where sjob_sched_id = @sched_id and (@all_users = 1 or sjob_owner = @owner)
				select @err=@@error
				if @err = 0 and @rows > 0
				begin
					select 'and scheduled jobs:'
					select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=sjob_name
					from sybmgmtdb..js_scheduledjobs where sjob_sched_id = @sched_id and
						(@all_users = 1 or sjob_owner = @owner)
				end
			    end
			    else
			    begin
				select 'sp_sjobdrop @name=''' + convert(varchar(64), @name) + ''', @option=''' + convert(varchar(512), @option) + ''' would drop schedule:'
				select sched_id=sched_id, sched_name=convert(varchar(64), sched_name)
					from sybmgmtdb..js_schedules where sched_id = @sched_id

				select @rows=count(sjob_id) from sybmgmtdb..js_scheduledjobs
				where sjob_sched_id = @sched_id and (@all_users = 1 or sjob_owner = @owner)
				select @err=@@error
				if @err = 0 and @rows > 0
				begin
					select 'and scheduled jobs:'
					select sjob_id=sjob_id, sjob_owner=sjob_owner, sjob_name=convert(varchar(64), sjob_name)
					from sybmgmtdb..js_scheduledjobs where sjob_sched_id = @sched_id and
						(@all_users = 1 or sjob_owner = @owner)
				end
			    end
				rollback tran nested_tran
				commit tran
				return 0
			end
			-- check running
			if @force = 1
				select @sjob_id = NULL
			else
				select @sjob_id=jsh_sjobid from sybmgmtdb..js_history where
					( jsh_state like '[QR]%' or jsh_state like '[CTX]1' ) and
					  jsh_sjobid in ( select sjob_id from sybmgmtdb..js_scheduledjobs where
							(sjob_sched_id = @sched_id       ) and
							(@all_users = 1 or sjob_owner = @owner) )
			if @sjob_id is not NULL
			begin
				rollback tran nested_tran
				commit tran
				-- 19072 'Procedure %1!, unable to perform the operation while running jobs are using %2!.'
				select @opt_val_pair='scheduled job id=' + convert(varchar(16), @sjob_id)
                		select @vcbuf1=@opt_val_pair
				raiserror 19072, @sp_name, @vcbuf1
				return -@@error
			end
			delete from sybmgmtdb..js_scheduledjobs where sjob_sched_id = @sched_id and
				(@all_users = 1 or sjob_owner = @owner)
			select @err=@@error
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
				raiserror 19073, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
			-- we update locked all sjobs using sched_id, but may not have deleted them all
			update sybmgmtdb..js_scheduledjobs set sjob_update=0 where sjob_update=@@spid
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
		-- delete schedule
		-- return
		delete from sybmgmtdb..js_schedules where sched_id = @sched_id
		select @err=@@error
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
			raiserror 19073, @sp_name, 'js_schedules', @err
			return -@@error
		end
		commit tran
		-- tell ASE
		if @sjob_count is NULL or @sjob_count = 0
			return 0
		declare sjobdrop cursor for select sjob_id from #sjobdrop_2
			for read only
		open sjobdrop
		fetch sjobdrop into @sjob_id
		while @@sqlstatus = 0
		begin
			if not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id)
				exec sp_js_wakeup 'job_deleted', @sjob_id
			fetch sjobdrop into @sjob_id
		end
		close sjobdrop
		deallocate cursor sjobdrop
		return 0
	end

	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobdrop')
begin
	print 'Created sp_sjobdrop'
	grant execute on sp_sjobdrop to js_user_role
	grant execute on sp_sjobdrop to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_sjobhelp')
	drop proc sp_sjobhelp
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobhelp  @name univarchar(),  @option univarchar()
--
--      @name is the name or id of a scheduled job, a job, a schedule or
--      runid.
--      The selection is made by using a prefix of sjname=, jname=, sname= or runid=.
--      With no prefix the default is the name or id of a scheduled job.
--      Example:-
--              'sjname=scheduled_job_name_or_id'
--              'jname=job_name_or_id'
--
--      @option is a list of control options to the procedure, valid options
--      are 'report', 'list', 'jobs', 'schedules', 'scheduledjobs', 
--      'running', 'scheduled', 'unscheduled',
--      'all_users', 'owner' and 'user'.
--      Example:-
--              @option='report,jobs'
--
--      The 'all_users', 'owner' and 'user' options may also be used to restrict
--      the scope of sp_sjobhelp, they are only available to callers with js_admin_role role.
--
create proc sp_sjobhelp (
	@name		univarchar(128) = NULL,
	@option		univarchar(512) = NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(128), @opt_name univarchar(32), @opt_value univarchar(96)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128), @vc_conv int
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @sp_name varchar(32), @jname_val univarchar(64), @owner_val varchar(30), @user_val varchar(30)
	declare @err int, @rows int, @msgno int, @is_admin int
	declare @sjob_id int, @job_id int, @sched_id int, @run_id int
	declare @all_arg int, @owner_arg int, @user_arg int, @id_arg int
	declare @list_val varchar(16), @list varchar(16), @sname_val univarchar(64), @sjname_val univarchar(64)
	declare @max_id int, @max_id2 int, @max_timeout int, @max_interval int, @max_jid int, @max_sid int
	declare @max_name1 int, @max_name2 int, @max_user1 int, @max_user2 int, @max_smsg int, @max_lmsg int, @max_date int
	declare @max_name3 int, @max_spid int
	-- 
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobhelp'
	select @list='report', @all_arg=0, @user_arg=0, @owner_arg=0, @id_arg=0, @vc_conv=1
	select @sjob_id=-1, @job_id=-1, @sched_id=-1, @run_id=-1, @jname_val=NULL, @sname_val=NULL, @sjname_val=NULL

	set nocount on
	select @is_admin=proc_role('js_admin_role')
	select @value=ltrim(rtrim(@option))
	--
	-- Get and validate the name or id of the scheduled job, job, schedule or runnid.
	--
	select @opt_val_pair = ltrim(rtrim(@name))
	if @name is not NULL
	begin
		select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		if @eq_pos <= 0				-- no prefix, defaults to scheduled job
			select @opt_name='sjname', @opt_value=@opt_val_pair
		else if @eq_pos = @opt_val_len		-- opt_name=  error
		begin
			-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                	select @vcbuf1=@opt_val_pair
			raiserror 19098, @sp_name, @vcbuf1
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))
			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value = ltrim(rtrim(@opt_value))
		end
	end
	else	select @opt_name=NULL
	--
	--
	--
	if @opt_name = 'sjname'
	begin
		--
		-- the name or id of a scheduled job
		--
		exec @sjob_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
		if @sjob_id = -19097
		begin
			select @id_arg=1, @job_id=-1, @sched_id=-1, @run_id=-1, @sjob_id=-2,
				@jname_val=NULL, @sname_val=NULL, @sjname_val=@opt_value
		end
		else if @sjob_id < 0
		begin
			select @msgno = abs(@sjob_id), @vcbuf1=@opt_name
			raiserror @msgno, @sp_name, @vcbuf1
			return -@@error
		end
		else	select @id_arg=1, @job_id=-1, @sched_id=-1, @run_id=-1,
				@jname_val=NULL, @sname_val=NULL, @sjname_val=NULL
		if @list_val is NULL select @list_val='scheduled'
		if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
	end
	else if @opt_name = 'jname'
	begin
		-- the name or id of a job
		--
		exec @job_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
		if @job_id = -19097
		begin
			select @id_arg=1, @sjob_id=-1, @sched_id=-1, @run_id=-1, @job_id=-2,
				@jname_val=@opt_value, @sname_val=NULL, @sjname_val=NULL
		end
		else if @job_id < 0
		begin
			select @msgno = abs(@job_id), @vcbuf1=@opt_name
			raiserror @msgno, @sp_name, @vcbuf1
			return -@@error
		end
		else
		begin
			select @jname_val=job_name from sybmgmtdb..js_jobs where job_id=@job_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_jobs', @err
				return -@@error
			end
			select @id_arg=1, @sjob_id=-1, @sched_id=-1, @run_id=-1,
				@sname_val=NULL, @sjname_val=NULL
		end
		if @list_val is NULL select @list_val='jobs'
		if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
	end
	else if @opt_name = 'sname'
	begin
		-- the name or id of a schedule
		--
		exec @sched_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sched', @return_id=1, @is_admin=@is_admin
		if @sched_id = -19097
		begin
			select @id_arg=1, @sjob_id=-1, @sched_id=-2, @run_id=-1, @job_id=-1,
				@jname_val=NULL, @sname_val=@opt_value, @sjname_val=NULL
		end
		else if @sched_id < 0
		begin
			select @msgno = abs(@sched_id), @vcbuf1=@opt_name
			raiserror @msgno, @sp_name, @vcbuf1
			return -@@error
		end
		else
		begin
			select @sname_val=sched_name from sybmgmtdb..js_schedules where sched_id=@sched_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_schedules', @err
				return -@@error
			end
			select @id_arg=1, @sjob_id=-1, @job_id=-1, @run_id=-1,
				@jname_val=NULL, @sjname_val=NULL
		end
		if @list_val is NULL select @list_val='schedules'
		if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
	end
	else if @opt_name = 'runid'
	begin
		exec @run_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='jsh', @return_id=1, @is_admin=@is_admin
		if @run_id < 0
		begin
			select @msgno = abs(@run_id), @vcbuf1=@opt_name
			raiserror @msgno, @sp_name, @vcbuf1
			return -@@error
		end
		select @id_arg=1, @sjob_id=-1, @job_id=-1, @sched_id=-1,
			@jname_val=NULL, @sname_val=NULL, @sjname_val=NULL
		if @list_val is NULL select @list_val='running'
		if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
	end
	else if @opt_name is not NULL
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
		select @vcname=@name
		raiserror 19098, @sp_name, @vcname
		return -@@error
	end
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			select @opt_val_pair=ltrim(rtrim(@opt_val_pair))
			if @opt_val_pair = 'report' or @opt_val_pair = 'list'
			begin
				select @list=@opt_val_pair
				select @curpos=@end_pos + 1
				continue
			end
			else if @opt_val_pair = 'running' or @opt_val_pair = 'jobs'
				or @opt_val_pair = 'schedules' or @opt_val_pair = 'scheduledjobs'
				or @opt_val_pair = 'scheduled' or @opt_val_pair = 'unscheduled'
			begin
				select @list_val=@opt_val_pair
				select @curpos=@end_pos + 1
				continue
			end
			else if @opt_val_pair = 'all_users'
				select @opt_name=@opt_val_pair
			else
			begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_val_pair
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		
		if @opt_name = 'all_users' or @opt_name = 'owner' or @opt_name = 'user'
		begin
			-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner or all_users.'
			if @is_admin = 0
			begin
				raiserror 19077, @sp_name
				return -@@error
			end
			if @opt_name = 'owner' or @opt_name = 'user'
			begin
				-- We do not check the user name is valid, this is to allow for
				-- tidying up after a user has been deleted.
				--
				if @opt_name = 'owner'
					select @owner_val=@opt_value, @owner_arg=1, @all_arg=0
				else	select @user_val=@opt_value, @user_arg=1, @all_arg=0
			end
			else select @all_arg = 1, @owner_arg=0, @user_arg=0
		end
		--
		-- we turn on 'all' by default, if js_admin_role specifies a name or id.
		--
		else if @opt_name = 'sjname'
		begin
			--
			-- the name or id of a scheduled job
			--
			exec @sjob_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
			if @sjob_id = -19097
			begin
				select @id_arg=1, @job_id=-1, @sched_id=-1, @run_id=-1, @sjob_id=-2,
					@jname_val=NULL, @sname_val=NULL, @sjname_val=@opt_value
			end
			else if @sjob_id < 0
			begin
				select @msgno = abs(@sjob_id), @vcbuf1=@opt_name
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			else	select @id_arg=1, @job_id=-1, @sched_id=-1, @run_id=-1,
					@jname_val=NULL, @sname_val=NULL, @sjname_val=NULL
			if @list_val is NULL select @list_val='scheduled'
			if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
		end
		else if @opt_name = 'jname'
		begin
			-- the name or id of a job
			--
			exec @job_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
			if @job_id = -19097
			begin
				select @id_arg=1, @sjob_id=-1, @sched_id=-1, @run_id=-1, @job_id=-2,
					@jname_val=@opt_value, @sname_val=NULL, @sjname_val=NULL
			end
			else if @job_id < 0
			begin
				select @msgno = abs(@job_id), @vcbuf1=@opt_name
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			else
			begin
				-- may need to have a jname for joining js_history
				select @jname_val=job_name from sybmgmtdb..js_jobs where job_id=@job_id
				select @err=@@error, @rows=@@rowcount
				if @err != 0
				begin
					-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
					raiserror 19076, @sp_name, 'js_jobs', @err
					return -@@error
				end
				select @id_arg=1, @sjob_id=-1, @sched_id=-1, @run_id=-1,
					@sname_val=NULL, @sjname_val=NULL
			end
			if @list_val is NULL select @list_val='jobs'
			if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
		end
		else if @opt_name = 'sname'
		begin
			-- the name or id of a schedule
			--
			exec @sched_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sched', @return_id=1, @is_admin=@is_admin
			if @sched_id = -19097
			begin
				select @id_arg=1, @sjob_id=-1, @sched_id=-2, @run_id=-1, @job_id=-1,
					@jname_val=NULL, @sname_val=@opt_value, @sjname_val=NULL
			end
			else if @sched_id < 0
			begin
				select @msgno = abs(@sched_id), @vcbuf1=@opt_name
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			else
			begin
				-- may need to have a sname for joining js_history
				select @sname_val=sched_name from sybmgmtdb..js_schedules where sched_id=@sched_id
				select @err=@@error, @rows=@@rowcount
				if @err != 0
				begin
					-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
					raiserror 19076, @sp_name, 'js_schedules', @err
					return -@@error
				end
				select @id_arg=1, @sjob_id=-1, @job_id=-1, @run_id=-1,
					@jname_val=NULL, @sjname_val=NULL
			end
			if @list_val is NULL select @list_val='schedules'
			if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
		end
		else if @opt_name = 'runid'
		begin
			exec @run_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='jsh', @return_id=1, @is_admin=@is_admin
			if @run_id < 0
			begin
				select @msgno = abs(@run_id), @vcbuf1=@opt_name
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @id_arg=1, @sjob_id=-1, @job_id=-1, @sched_id=-1,
				@jname_val=NULL, @sname_val=NULL, @sjname_val=NULL
			if @list_val is NULL select @list_val='running'
			if @is_admin = 1 select @all_arg = 1, @owner_arg=0, @user_arg=0
		end
		else if @opt_name = 'varchar' or @opt_name = 'ascii'	select @vc_conv=1
		else if @opt_name = 'unichar' or @opt_name = 'utf8'	select @vc_conv=0
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
			select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end
		
		select @curpos=@end_pos + 1
	end

	select @err=0
	if @list_val = 'running'
	begin
		if @all_arg = 0 and @user_arg = 0 and @owner_arg = 0
			select @user_val = suser_name(), @user_arg=1
		if @list = 'list'
		begin
			if @sjname_val is not NULL
			begin
			    if @vc_conv = 0
			    begin
				select  sjob_runid=jsh_exid,		sjob_state=jsh_state,	
					sjob_start=jsh_jobstart,	sjob_user_req=jsh_user_req,
					sjob_server=sjob_server,	sjob_spid=jsh_spid,
					sjob_id=jsh_sjobid,
					job_name=jsh_jobname,		sched_name=jsh_schedname,
					sjob_user_run=jsh_user_run,
					sjob_short_message=jsh_smsg,	sjob_long_message=jsh_lmsg
				from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
				where	jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
							where sjob_name = @sjname_val)      and
					(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
					(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
					(@user_arg   = 0  or  jsh_user_req = @user_val)     and
					(jsh_sjobid  = sjob_id)
				order by jsh_jobstart asc
				select @err=@@error, @rows=@@rowcount
			    end
			    else
			    begin
				select  sjob_runid=jsh_exid,		sjob_state=jsh_state,	
					sjob_start=jsh_jobstart,	sjob_user_req=jsh_user_req,
					sjob_server=sjob_server,	sjob_spid=jsh_spid,
					sjob_id=jsh_sjobid,
					job_name=convert(varchar(64), jsh_jobname),
					sched_name=convert(varchar(64), jsh_schedname),
					sjob_user_run=jsh_user_run,
					sjob_short_message=convert(varchar(64), jsh_smsg),
					sjob_long_message=convert(varchar(255), jsh_lmsg)
				from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
				where	jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
							where sjob_name = @sjname_val)      and
					(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
					(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
					(@user_arg   = 0  or  jsh_user_req = @user_val)     and
					(jsh_sjobid  = sjob_id)
				order by jsh_jobstart asc
				select @err=@@error, @rows=@@rowcount
			    end
			end
			else
			begin
			    if @vc_conv = 0
			    begin
				select  sjob_runid=jsh_exid,		sjob_state=jsh_state,	
					sjob_start=jsh_jobstart,	sjob_user_req=jsh_user_req,
					sjob_server=sjob_server,	sjob_spid=jsh_spid,
					sjob_id=jsh_sjobid,
					job_name=jsh_jobname,		sched_name=jsh_schedname,
					sjob_user_run=jsh_user_run,
					sjob_short_message=jsh_smsg,	sjob_long_message=jsh_lmsg
				from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
				where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
					(@id_arg = 0 or jsh_exid = @run_id
							or jsh_sjobid = @sjob_id 
							or jsh_jobname = @jname_val
							or jsh_schedname = @sname_val)      and
					(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
					(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
					(@user_arg   = 0  or  jsh_user_req = @user_val)
				order by jsh_jobstart asc
				select @err=@@error, @rows=@@rowcount
			    end
			    else
			    begin
				select  sjob_runid=jsh_exid,		sjob_state=jsh_state,	
					sjob_start=jsh_jobstart,	sjob_user_req=jsh_user_req,
					sjob_server=sjob_server,	sjob_spid=jsh_spid,
					sjob_id=jsh_sjobid,
					job_name=convert(varchar(64), jsh_jobname),
					sched_name=convert(varchar(64), jsh_schedname),
					sjob_user_run=jsh_user_run,
					sjob_short_message=convert(varchar(64), jsh_smsg),
					sjob_long_message=convert(varchar(255), jsh_lmsg)
				from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
				where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
					(@id_arg = 0 or jsh_exid = @run_id
							or jsh_sjobid = @sjob_id 
							or jsh_jobname = @jname_val
							or jsh_schedname = @sname_val)      and
					(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
					(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
					(@user_arg   = 0  or  jsh_user_req = @user_val)
				order by jsh_jobstart asc
				select @err=@@error, @rows=@@rowcount
			    end
			end
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_schedules', @err
				return -@@error
			end
			return @err
		end
		--
		-- report
		--
		if @sjname_val is not NULL
		begin
			select  @max_id=max(jsh_exid), @max_id2=max(jsh_sjobid),
				@max_name1=max(char_length(jsh_jobname)), @max_name2=max(char_length(jsh_schedname)),
				@max_date=max(char_length(convert(varchar(64), jsh_jobstart))),
				@max_user1=max(char_length(jsh_user_run)), @max_user2=max(char_length(jsh_user_req)),
				@max_smsg=max(char_length(jsh_smsg)), @max_lmsg=max(char_length(jsh_lmsg)),
				@max_name3=max(char_length(sjob_server)), @max_spid=max(jsh_spid)
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
						where sjob_name = @sjname_val)      and
				(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
				(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
				(@user_arg   = 0  or  jsh_user_req = @user_val)     and
				(jsh_sjobid  = sjob_id)
			select @err=@@error, @rows=@@rowcount
		end
		else
		begin
			select  @max_id=max(jsh_exid), @max_id2=max(jsh_sjobid),
				@max_name1=max(char_length(jsh_jobname)), @max_name2=max(char_length(jsh_schedname)),
				@max_date=max(char_length(convert(varchar(64), jsh_jobstart))),
				@max_user1=max(char_length(jsh_user_run)), @max_user2=max(char_length(jsh_user_req)),
				@max_smsg=max(char_length(jsh_smsg)), @max_lmsg=max(char_length(jsh_lmsg)),
				@max_name3=max(char_length(sjob_server)), @max_spid=max(jsh_spid)
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id
						or jsh_sjobid = @sjob_id 
						or jsh_jobname = @jname_val
						or jsh_schedname = @sname_val)      and
				(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
				(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
				(@user_arg   = 0  or  jsh_user_req = @user_val)
			select @err=@@error, @rows=@@rowcount
		end
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_jobs', @err
			return -@@error
		end
		if @rows = 0
			return 0

		select  @max_id=char_length(convert(varchar(16), @max_id)),
			@max_id2=char_length(convert(varchar(16), @max_id2)),
			@max_spid=char_length(convert(varchar(16), @max_spid))
		if @max_id    is NULL or @max_id    < 6  select @max_id=6
		if @max_id2   is NULL or @max_id2   < 7  select @max_id2=7
		if @max_spid  is NULL or @max_spid  < 4  select @max_spid=4
		if @max_date  is NULL or @max_date  < 9  select @max_date=9
		if @max_name1 is NULL or @max_name1 < 8  select @max_name1=8
		if @max_name2 is NULL or @max_name2 < 13 select @max_name2=13
		if @max_name3 is NULL or @max_name3 < 6  select @max_name3=6
		if @max_user1 is NULL or @max_user1 < 8  select @max_user1=8
		if @max_user2 is NULL or @max_user2 < 8  select @max_user2=8
		if @max_smsg  is NULL or @max_smsg  < 13 select @max_smsg=13
		if @max_lmsg  is NULL or @max_lmsg  < 12 select @max_lmsg=12

		if @vc_conv = 0
		begin
		    select @value=replicate(' ', 260)

		    select  'run_id'	+ substring(@value, 1, @max_id -6+2) +
			'state  '	+
			'job start'	+ substring(@value, 1, @max_date -9+2) +
			'user_req'	+ substring(@value, 1, @max_user2 -8+2) +
			'server'	+ substring(@value, 1, @max_name3 -6+2) +
			'spid'		+ substring(@value, 1, @max_spid -4+2) +
			'sjob_id'	+ substring(@value, 1, @max_id2 -7+2) +
			'job name'	+ substring(@value, 1, @max_name1 -8+2) +
			'schedule name'	+ substring(@value, 1, @max_name2 -13+2) +
			'user_run'	+ substring(@value, 1, @max_user1 -8+2) +
			'short message'	+ substring(@value, 1, @max_smsg -13+2) +
			'long message'	+ substring(@value, 1, @max_lmsg -12+2)
		end
		else
		begin
		    select @vcbuf1=replicate(' ', 260)

		    select  'run_id'	+ substring(@vcbuf1, 1, @max_id -6+2) +
			'state  '	+
			'job start'	+ substring(@vcbuf1, 1, @max_date -9+2) +
			'user_req'	+ substring(@vcbuf1, 1, @max_user2 -8+2) +
			'server'	+ substring(@vcbuf1, 1, @max_name3 -6+2) +
			'spid'		+ substring(@vcbuf1, 1, @max_spid -4+2) +
			'sjob_id'	+ substring(@vcbuf1, 1, @max_id2 -7+2) +
			'job name'	+ substring(@vcbuf1, 1, @max_name1 -8+2) +
			'schedule name'	+ substring(@vcbuf1, 1, @max_name2 -13+2) +
			'user_run'	+ substring(@vcbuf1, 1, @max_user1 -8+2) +
			'short message'	+ substring(@vcbuf1, 1, @max_smsg -13+2) +
			'long message'	+ substring(@vcbuf1, 1, @max_lmsg -12+2)
		end

		-- TODO job_start
		if @sjname_val is not NULL
		begin
		    if @vc_conv = 0
		    begin
			select  str(jsh_exid, @max_id) + '  ' +
				convert(char(5), jsh_state) + '  ' +
				convert(varchar(48), jsh_jobstart) + '  ' +
				substring(jsh_user_req, 1, @max_user2) +
					substring(@value, 1, @max_user2 - isnull(char_length(jsh_user_req),0)) + '  ' +
				substring(sjob_server, 1, @max_name3) +
					substring(@value, 1, @max_name3 - isnull(char_length(sjob_server),0)) + '  ' +
				str(jsh_spid, @max_spid) + '  ' +
				str(jsh_sjobid, @max_id2) + '  ' +
				substring(jsh_jobname, 1, @max_name1) +
					substring(@value, 1, @max_name1 - isnull(char_length(jsh_jobname),0)) + '  ' +
				substring(jsh_schedname, 1, @max_name2) +
					substring(@value, 1, @max_name2 - isnull(char_length(jsh_schedname),0)) + '  ' +
				substring(jsh_user_run, 1, @max_user1) +
					substring(@value, 1, @max_user1 - isnull(char_length(jsh_user_run),0)) + '  ' +
				substring(jsh_smsg, 1, @max_smsg) +
					substring(@value, 1, @max_smsg - isnull(char_length(jsh_smsg),0)) + '  ' +
				substring(jsh_lmsg, 1, @max_lmsg) +
					substring(@value, 1, @max_lmsg - isnull(char_length(jsh_lmsg),0))
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs  readpast
			where	jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
						where sjob_name = @sjname_val)      and
				(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
				(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
				(@user_arg   = 0  or  jsh_user_req = @user_val)     and
				(jsh_sjobid  = sjob_id)
			order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select  str(jsh_exid, @max_id) + '  ' +
				convert(char(5), jsh_state) + '  ' +
				convert(varchar(48), jsh_jobstart) + '  ' +
				substring(jsh_user_req, 1, @max_user2) +
					substring(@value, 1, @max_user2 - isnull(char_length(jsh_user_req),0)) + '  ' +
				substring(sjob_server, 1, @max_name3) +
					substring(@value, 1, @max_name3 - isnull(char_length(sjob_server),0)) + '  ' +
				str(jsh_spid, @max_spid) + '  ' +
				str(jsh_sjobid, @max_id2) + '  ' +
				convert(varchar(64),
				substring(jsh_jobname, 1, @max_name1) +
					substring(@value, 1, @max_name1 - isnull(char_length(jsh_jobname),0)) ) + '  ' +
				convert(varchar(64),
				substring(jsh_schedname, 1, @max_name2) +
					substring(@value, 1, @max_name2 - isnull(char_length(jsh_schedname),0)) ) + '  ' +
				substring(jsh_user_run, 1, @max_user1) +
					substring(@value, 1, @max_user1 - isnull(char_length(jsh_user_run),0)) + '  ' +
				convert(varchar(64),
				substring(jsh_smsg, 1, @max_smsg) +
					substring(@value, 1, @max_smsg - isnull(char_length(jsh_smsg),0)) ) + '  ' +
				convert(varchar(255),
				substring(jsh_lmsg, 1, @max_lmsg) +
					substring(@value, 1, @max_lmsg - isnull(char_length(jsh_lmsg),0)) )
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs  readpast
			where	jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
						where sjob_name = @sjname_val)      and
				(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
				(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
				(@user_arg   = 0  or  jsh_user_req = @user_val)     and
				(jsh_sjobid  = sjob_id)
			order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
		    end
		end
		else
		begin
		    if @vc_conv = 0
		    begin
			select  str(jsh_exid, @max_id) + '  ' +
				convert(char(5), jsh_state) + '  ' +
				convert(varchar(48), jsh_jobstart) + '  ' +
				substring(jsh_user_req, 1, @max_user2) +
					substring(@value, 1, @max_user2 - isnull(char_length(jsh_user_req),0)) + '  ' +
				substring(sjob_server, 1, @max_name3) +
					substring(@value, 1, @max_name3 - isnull(char_length(sjob_server),0)) + '  ' +
				str(jsh_spid, @max_spid) + '  ' +
				str(jsh_sjobid, @max_id2) + '  ' +
				substring(jsh_jobname, 1, @max_name1) +
					substring(@value, 1, @max_name1 - isnull(char_length(jsh_jobname),0)) + '  ' +
				substring(jsh_schedname, 1, @max_name2) +
					substring(@value, 1, @max_name2 - isnull(char_length(jsh_schedname),0)) + '  ' +
				substring(jsh_user_run, 1, @max_user1) +
					substring(@value, 1, @max_user1 - isnull(char_length(jsh_user_run),0)) + '  ' +
				substring(jsh_smsg, 1, @max_smsg) +
					substring(@value, 1, @max_smsg - isnull(char_length(jsh_smsg),0)) + '  ' +
				substring(jsh_lmsg, 1, @max_lmsg) +
					substring(@value, 1, @max_lmsg - isnull(char_length(jsh_lmsg),0))
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id
						or jsh_sjobid = @sjob_id 
						or jsh_jobname = @jname_val
						or jsh_schedname = @sname_val)      and
				(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
				(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
				(@user_arg   = 0  or  jsh_user_req = @user_val)
			order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select  str(jsh_exid, @max_id) + '  ' +
				convert(char(5), jsh_state) + '  ' +
				convert(varchar(48), jsh_jobstart) + '  ' +
				substring(jsh_user_req, 1, @max_user2) +
					substring(@value, 1, @max_user2 - isnull(char_length(jsh_user_req),0)) + '  ' +
				substring(sjob_server, 1, @max_name3) +
					substring(@value, 1, @max_name3 - isnull(char_length(sjob_server),0)) + '  ' +
				str(jsh_spid, @max_spid) + '  ' +
				str(jsh_sjobid, @max_id2) + '  ' +
				convert(varchar(64),
				substring(jsh_jobname, 1, @max_name1) +
					substring(@value, 1, @max_name1 - isnull(char_length(jsh_jobname),0)) ) + '  ' +
				convert(varchar(64),
				substring(jsh_schedname, 1, @max_name2) +
					substring(@value, 1, @max_name2 - isnull(char_length(jsh_schedname),0)) ) + '  ' +
				substring(jsh_user_run, 1, @max_user1) +
					substring(@value, 1, @max_user1 - isnull(char_length(jsh_user_run),0)) + '  ' +
				convert(varchar(64),
				substring(jsh_smsg, 1, @max_smsg) +
					substring(@value, 1, @max_smsg - isnull(char_length(jsh_smsg),0)) ) + '  ' +
				convert(varchar(255),
				substring(jsh_lmsg, 1, @max_lmsg) +
					substring(@value, 1, @max_lmsg - isnull(char_length(jsh_lmsg),0)) )
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id
						or jsh_sjobid = @sjob_id 
						or jsh_jobname = @jname_val
						or jsh_schedname = @sname_val)      and
				(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
				(@owner_arg  = 0  or  jsh_user_run = @owner_val)    and
				(@user_arg   = 0  or  jsh_user_req = @user_val)
			order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
		    end
		end
		return @err
	end
	--
	-- select owner and shared by default.
	--
	if @all_arg = 0 and @user_arg = 0 and @owner_arg = 0
		select @owner_val = suser_name(), @owner_arg=0
	if @list_val = 'jobs'
	begin
		if @list = 'list'
		begin
		    if @vc_conv = 0
		    begin
			select  job_id=job_id,		job_name=job_name,
				job_description=job_description,
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout
			from sybmgmtdb..js_jobs where
				(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
				(@all_arg = 1
				  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
				  or (@owner_arg = 1 and  job_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		    else
		    begin
			select  job_id=job_id,		job_name=convert(varchar(64), job_name),
				job_description=convert(varchar(128), job_description),
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout
			from sybmgmtdb..js_jobs where
				(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
				(@all_arg = 1
				  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
				  or (@owner_arg = 1 and  job_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		end
		-- report
		select  @max_id=max(char_length(convert(varchar(16), job_id))),
			@max_timeout=max(char_length(convert(varchar(16), job_default_timeout)))
		from sybmgmtdb..js_jobs where
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount

		if @vc_conv = 0
		begin
		    select	'job_id: ' + str(job_id, @max_id) + '  name: ''' + job_name + ''''
			+ char(10) + '    description: ' + job_description
			+ char(10) + '    owner      : ' + job_owner
			+ char(10) + '    created    : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties : ' + job_uproperties,
			  char(10) + '    properties : ' )
				+ nullif (
			  char(10) + '    timeout    : ' + str(nullif(job_default_timeout,0), @max_timeout),
			  char(10) + '    timeout    : ' ) +
			  char(10)
		    from sybmgmtdb..js_jobs where
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		    select @err=@@error
		    return @err
		end
		else
		begin
		    select	'job_id: ' + str(job_id, @max_id) + '  name: ''' + convert(varchar(64), job_name) + ''''
			+ char(10) + '    description: ' + convert(varchar(128), job_description)
			+ char(10) + '    owner      : ' + job_owner
			+ char(10) + '    created    : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties : ' + job_uproperties,
			  char(10) + '    properties : ' )
				+ nullif (
			  char(10) + '    timeout    : ' + str(nullif(job_default_timeout,0), @max_timeout),
			  char(10) + '    timeout    : ' ) +
			  char(10)
		    from sybmgmtdb..js_jobs where
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		    select @err=@@error
		    return @err
		end
	end
	if @list_val = 'schedules'
	begin
		if @list = 'list'
		begin
		    if @vc_conv = 0
		    begin
			select	sched_id=sched_id,	sched_name=sched_name,
				sched_description=sched_description,
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates
			from sybmgmtdb..js_schedules where
				(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
				  or (@owner_arg = 1 and  sched_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		    else
		    begin
			select	sched_id=sched_id,	sched_name=convert(varchar(64), sched_name),
				sched_description=convert(varchar(128), sched_description),
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates
			from sybmgmtdb..js_schedules where
				(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
				  or (@owner_arg = 1 and  sched_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		end

		select  @max_id=max(char_length(convert(varchar(16), sched_id))),
			@max_interval=max(char_length(convert(varchar(16), sched_interval)))
		from sybmgmtdb..js_schedules where
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val)
		select @err=@@error, @rows=@@rowcount

		if @vc_conv = 0
		begin
		    select	'sched_id: ' + str(sched_id, @max_id) + '  name: ''' + sched_name + ''''
			+ char(10) + '    description: ' + sched_description
			+ char(10) + '    owner      : ' + sched_owner
			+ char(10) + '    created    : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties : ' + sched_uproperties,
			  char(10) + '    properties : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating  : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating  : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating  : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate  : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate  : ' ) +
				nullif (
			  char(10) + '    enddate    : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate    : ' ) +
			  char(10)
		    from sybmgmtdb..js_schedules where
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
			  or (@owner_arg = 1 and  sched_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    return @err
		end
		else
		begin
		    select	'sched_id: ' + str(sched_id, @max_id) + '  name: ''' + convert(varchar(64), sched_name) + ''''
			+ char(10) + '    description: ' + convert(varchar(128), sched_description)
			+ char(10) + '    owner      : ' + sched_owner
			+ char(10) + '    created    : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties : ' + sched_uproperties,
			  char(10) + '    properties : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating  : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating  : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating  : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate  : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate  : ' ) +
				nullif (
			  char(10) + '    enddate    : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate    : ' ) +
			  char(10)
		    from sybmgmtdb..js_schedules where
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
			  or (@owner_arg = 1 and  sched_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    return @err
		end
	end
	if @list_val = 'scheduledjobs'
	begin
		if @list = 'list'
		begin
		    if @vc_conv = 0
		    begin
			select	sjob_id=sjob_id, sjob_job_id=sjob_job_id, sjob_sched_id=sjob_sched_id,
				job_name=job_name,	sched_name=sched_name,
				sjob_owner=sjob_owner,	sjob_created=sjob_created,
				sjob_enable=sjob_enable, sjob_properties=sjob_uproperties,
				sjob_server=sjob_server, sjob_locale=sjob_locale,
				sjob_timeout_value=sjob_timeout_value
			from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
				(js_scheduledjobs.sjob_job_id    = js_jobs.job_id)        and
				(js_scheduledjobs.sjob_sched_id  = js_schedules.sched_id) and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
						or sjob_sched_id = @sched_id or sjob_name = @sjname_val
						or job_name = @jname_val or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
				  or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		    else
		    begin
			select	sjob_id=sjob_id, sjob_job_id=sjob_job_id, sjob_sched_id=sjob_sched_id,
				job_name=convert(varchar(64), job_name),
				sched_name=convert(varchar(64), sched_name),
				sjob_owner=sjob_owner,	sjob_created=sjob_created,
				sjob_enable=sjob_enable, sjob_properties=sjob_uproperties,
				sjob_server=sjob_server, sjob_locale=sjob_locale,
				sjob_timeout_value=sjob_timeout_value
			from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
				(js_scheduledjobs.sjob_job_id    = js_jobs.job_id)        and
				(js_scheduledjobs.sjob_sched_id  = js_schedules.sched_id) and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
						or sjob_sched_id = @sched_id or sjob_name = @sjname_val
						or job_name = @jname_val or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
				  or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		end
		--
		-- report
		--
		select	@max_id =max(char_length(convert(varchar(16), sjob_id))),
			@max_jid=max(char_length(convert(varchar(16), sjob_job_id))),
			@max_sid=max(char_length(convert(varchar(16), sjob_sched_id))),
			@max_timeout=max(char_length(convert(varchar(16), sjob_timeout_value)))
		from sybmgmtdb..js_scheduledjobs
		select @err=@@error, @rows=@@rowcount
		if @max_sid > @max_jid select @max_jid = @max_sid

		if @vc_conv = 0
		begin
		    select	'sjob_id: ' + str(sjob_id, @max_id) + '  name: ''' + sjob_name + ''''
			+ char(10) + '    owner         : ' + sjob_owner
			+ char(10) + '    created       : ' + convert(varchar(64), sjob_created)
			+ char(10) + '    state         : ' +
				substring('enabled', 1 - abs(sign(sjob_enable - 1)), 7) +
				substring('disabled', abs(sign(sjob_enable - 1)), 8)
			+ char(10) + '    job name      : ' + str(sjob_job_id, @max_jid)   + ' - '''+job_name+''''
			+ char(10) + '    schedule name : ' + str(sjob_sched_id, @max_jid) + ' - '''+sched_name+''''
				+ nullif (
			  char(10) + '    properties    : ' + sjob_uproperties,
			  char(10) + '    properties    : ' ) 
				+ nullif (
			  char(10) + '    server        : ' + sjob_server,
			  char(10) + '    server        : ' )
				+ nullif (
			  char(10) + '    locale        : ' + sjob_locale,
			  char(10) + '    locale        : ' )
				+ nullif (
			  char(10) + '    timeout       : ' + str(nullif(sjob_timeout_value, 0), @max_timeout),
			  char(10) + '    timeout       : ' ) +
			  char(10)
		    from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
			(js_scheduledjobs.sjob_job_id    = js_jobs.job_id)        and
			(js_scheduledjobs.sjob_sched_id  = js_schedules.sched_id) and
			(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val
					or job_name = @jname_val or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  or (@owner_arg = 1 and  sjob_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    return @err
		end
		else
		begin
		    select	'sjob_id: ' + str(sjob_id, @max_id) + '  name: ''' + convert(varchar(64), sjob_name) + ''''
			+ char(10) + '    owner         : ' + sjob_owner
			+ char(10) + '    created       : ' + convert(varchar(64), sjob_created)
			+ char(10) + '    state         : ' +
				substring('enabled', 1 - abs(sign(sjob_enable - 1)), 7) +
				substring('disabled', abs(sign(sjob_enable - 1)), 8)
			+ char(10) + '    job name      : ' + str(sjob_job_id, @max_jid)   + ' - '''+ convert(varchar(64), job_name) +''''
			+ char(10) + '    schedule name : ' + str(sjob_sched_id, @max_jid) + ' - '''+ convert(varchar(64), sched_name) +''''
				+ nullif (
			  char(10) + '    properties    : ' + sjob_uproperties,
			  char(10) + '    properties    : ' ) 
				+ nullif (
			  char(10) + '    server        : ' + sjob_server,
			  char(10) + '    server        : ' )
				+ nullif (
			  char(10) + '    locale        : ' + sjob_locale,
			  char(10) + '    locale        : ' )
				+ nullif (
			  char(10) + '    timeout       : ' + str(nullif(sjob_timeout_value, 0), @max_timeout),
			  char(10) + '    timeout       : ' ) +
			  char(10)
		    from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
			(js_scheduledjobs.sjob_job_id    = js_jobs.job_id)        and
			(js_scheduledjobs.sjob_sched_id  = js_schedules.sched_id) and
			(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val
					or job_name = @jname_val or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  or (@owner_arg = 1 and  sjob_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    return @err
		end
	end

	if @list_val is NULL or @list_val = 'scheduled'
	begin
		if @list = 'list'
		begin
		    if @vc_conv = 0
		    begin
			select	sjob_id=sjob_id,	sjob_name=sjob_name,
				job_id=job_id,		job_name=job_name,
				sched_id=sched_id,	sched_name=sched_name,
				sjob_enable=sjob_enable,sjob_properties=sjob_uproperties,
				sjob_owner=sjob_owner,	sjob_created=sjob_created,
				sjob_server=sjob_server,sjob_timeout_value=sjob_timeout_value,

				job_description=job_description,
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id,

				sched_description=sched_description,
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates

			from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
				(js_scheduledjobs.sjob_job_id   = js_jobs.job_id)   and
				(js_scheduledjobs.sjob_sched_id = js_schedules.sched_id) and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val
					or job_name = @jname_val or sched_name = @sname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			if @list_val = 'scheduled' return @err
		    end
		    else
		    begin
			select	sjob_id=sjob_id,	sjob_name=convert(varchar(64), sjob_name),
				job_id=job_id,		job_name=convert(varchar(64), job_name),
				sched_id=sched_id,	sched_name=convert(varchar(64), sched_name),
				sjob_enable=sjob_enable,sjob_properties=sjob_uproperties,
				sjob_owner=sjob_owner,	sjob_created=sjob_created,
				sjob_server=sjob_server,sjob_timeout_value=sjob_timeout_value,

				job_description=convert(varchar(128), job_description),
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id,

				sched_description=convert(varchar(128), sched_description),
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates

			from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
				(js_scheduledjobs.sjob_job_id   = js_jobs.job_id)   and
				(js_scheduledjobs.sjob_sched_id = js_schedules.sched_id) and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val
					or job_name = @jname_val or sched_name = @sname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			if @list_val = 'scheduled' return @err
		    end
		end
		else
		begin
		--
		-- report
		--
		select	@max_id =max(char_length(convert(varchar(16), sjob_id))),
			@max_jid=max(char_length(convert(varchar(16), sjob_job_id))),
			@max_sid=max(char_length(convert(varchar(16), sjob_sched_id))),
			@max_timeout=max(char_length(convert(varchar(16), sjob_timeout_value)))
		from sybmgmtdb..js_scheduledjobs
		select @err=@@error, @rows=@@rowcount
		if @max_sid > @max_jid select @max_jid = @max_sid
		select  @max_interval=max(char_length(convert(varchar(16), sched_interval)))
		from sybmgmtdb..js_schedules
		select @err=@@error, @rows=@@rowcount

		if @vc_conv = 0
		begin
		    select	'sjob_id: ' + str(sjob_id, @max_id) + '  name: ''' + sjob_name + ''''
			+ char(10) + '    owner          : ' + sjob_owner
			+ char(10) + '    created        : ' + convert(varchar(64), sjob_created)
			+ char(10) + '    state          : ' +
				substring('enabled', 1 - abs(sign(sjob_enable - 1)), 7) +
				substring('disabled', abs(sign(sjob_enable - 1)), 8)
			+ char(10) + '    job name       : ' + str(sjob_job_id, @max_jid)   + ' - '''+job_name+''''
			+ char(10) + '    schedule name  : ' + str(sjob_sched_id, @max_jid) + ' - '''+sched_name+''''
				+ nullif (
			  char(10) + '    properties     : ' + sjob_uproperties,
			  char(10) + '    properties     : ' ) 
				+ nullif (
			  char(10) + '    server         : ' + sjob_server,
			  char(10) + '    server         : ' )
				+ nullif (
			  char(10) + '    locale         : ' + sjob_locale,
			  char(10) + '    locale         : ' )
				+ nullif (
			  char(10) + '    timeout        : ' + str(nullif(sjob_timeout_value, 0), @max_timeout),
			  char(10) + '    timeout        : ' )

			+ char(10) + '    -- job --------: '
			+ char(10) + '    description    : ' + job_description
			+ char(10) + '    owner          : ' + job_owner
			+ char(10) + '    created        : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties     : ' + job_uproperties,
			  char(10) + '    properties     : ' )
				+ nullif (
			  char(10) + '    default timeout: ' + convert(varchar(10), nullif(job_default_timeout,0)),
			  char(10) + '    default timeout: ')

			+ char(10) + '    -- schedule ---: '
			+ char(10) + '    description    : ' + sched_description
			+ char(10) + '    owner          : ' + sched_owner
			+ char(10) + '    created        : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties     : ' + sched_uproperties,
			  char(10) + '    properties     : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days        : ' + sched_udays,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udates,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating      : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating      : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' ) +
				nullif (
			  char(10) + '    endtime        : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udays,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udates,
			  char(10) + '    on days        : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating      : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' ) +
				nullif (
			  char(10) + '    endtime        : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udays,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udates,
			  char(10) + '    on days        : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate      : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate      : ' ) +
				nullif (
			  char(10) + '    enddate        : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate        : ' ) +
			  char(10)
		
		    from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
			(js_scheduledjobs.sjob_job_id    = js_jobs.job_id)        and
			(js_scheduledjobs.sjob_sched_id  = js_schedules.sched_id) and
			(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
				or sjob_sched_id = @sched_id or sjob_name = @sjname_val
				or job_name = @jname_val or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  or (@owner_arg = 1 and  sjob_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    if @list_val = 'scheduled' return @err
		end
		else -- vc_conv != 0
		begin
		    select	'sjob_id: ' + str(sjob_id, @max_id) + '  name: ''' + convert(varchar(64), sjob_name) + ''''
			+ char(10) + '    owner          : ' + sjob_owner
			+ char(10) + '    created        : ' + convert(varchar(64), sjob_created)
			+ char(10) + '    state          : ' +
				substring('enabled', 1 - abs(sign(sjob_enable - 1)), 7) +
				substring('disabled', abs(sign(sjob_enable - 1)), 8)
			+ char(10) + '    job name       : ' + str(sjob_job_id, @max_jid)   + ' - '''+convert(varchar(64), job_name)+''''
			+ char(10) + '    schedule name  : ' + str(sjob_sched_id, @max_jid) + ' - '''+convert(varchar(64), sched_name)+''''
				+ nullif (
			  char(10) + '    properties     : ' + sjob_uproperties,
			  char(10) + '    properties     : ' ) 
				+ nullif (
			  char(10) + '    server         : ' + sjob_server,
			  char(10) + '    server         : ' )
				+ nullif (
			  char(10) + '    locale         : ' + sjob_locale,
			  char(10) + '    locale         : ' )
				+ nullif (
			  char(10) + '    timeout        : ' + str(nullif(sjob_timeout_value, 0), @max_timeout),
			  char(10) + '    timeout        : ' )

			+ char(10) + '    -- job --------: '
			+ char(10) + '    description    : ' + convert(varchar(128), job_description)
			+ char(10) + '    owner          : ' + job_owner
			+ char(10) + '    created        : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties     : ' + job_uproperties,
			  char(10) + '    properties     : ' )
				+ nullif (
			  char(10) + '    default timeout: ' + convert(varchar(10), nullif(job_default_timeout,0)),
			  char(10) + '    default timeout: ')

			+ char(10) + '    -- schedule ---: '
			+ char(10) + '    description    : ' + convert(varchar(128), sched_description)
			+ char(10) + '    owner          : ' + sched_owner
			+ char(10) + '    created        : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties     : ' + sched_uproperties,
			  char(10) + '    properties     : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days        : ' + sched_udays,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udates,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating      : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating      : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' ) +
				nullif (
			  char(10) + '    endtime        : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udays,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udates,
			  char(10) + '    on days        : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating      : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime      : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime      : ' ) +
				nullif (
			  char(10) + '    endtime        : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udays,
			  char(10) + '    on days        : ' ) +
				nullif (
			  char(10) + '    on days        : ' + sched_udates,
			  char(10) + '    on days        : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate      : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate      : ' ) +
				nullif (
			  char(10) + '    enddate        : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate        : ' ) +
			  char(10)
		
		    from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules where
			(js_scheduledjobs.sjob_job_id    = js_jobs.job_id)        and
			(js_scheduledjobs.sjob_sched_id  = js_schedules.sched_id) and
			(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
				or sjob_sched_id = @sched_id or sjob_name = @sjname_val
				or job_name = @jname_val or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  or (@owner_arg = 1 and  sjob_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    if @list_val = 'scheduled' return @err
		end -- vc_conv != 0
		end
	end

	if @list_val = 'unscheduled'
	begin
		if @list = 'list'
		begin
		    if @vc_conv = 0
		    begin
			select  job_id=job_id,		job_name=job_name,
				job_description=job_description,
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout
			from sybmgmtdb..js_jobs where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
				(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
				(@all_arg = 1
				  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
				  or (@owner_arg = 1 and  job_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount

			select	sched_id=sched_id,	sched_name=sched_name,
				sched_description=sched_description,
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates
			from sybmgmtdb..js_schedules where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_sched_id = js_schedules.sched_id) and
				(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
				  or (@owner_arg = 1 and  sched_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			if @list_val = 'unscheduled' return @err
		    end
		    else
		    begin
			select  job_id=job_id,		job_name=convert(varchar(64), job_name),
				job_description=convert(varchar(128), job_description),
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout
			from sybmgmtdb..js_jobs where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
				(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
				(@all_arg = 1
				  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
				  or (@owner_arg = 1 and  job_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount

			select	sched_id=sched_id,	sched_name=convert(varchar(64), sched_name),
				sched_description=convert(varchar(128), sched_description),
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates
			from sybmgmtdb..js_schedules where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_sched_id = js_schedules.sched_id) and
				(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
				  or (@owner_arg = 1 and  sched_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			if @list_val = 'unscheduled' return @err
		    end
		end
		else
		begin
		-- report
		select  @max_id=max(char_length(convert(varchar(16), job_id))),
			@max_timeout=max(char_length(convert(varchar(16), job_default_timeout)))
		from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount

		if @vc_conv = 0
		begin
		    select	'job_id: ' + str(job_id, @max_id) + '  name: ''' + job_name + ''''
			+ char(10) + '    description: ' + job_description
			+ char(10) + '    owner      : ' + job_owner
			+ char(10) + '    created    : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties : ' + job_uproperties,
			  char(10) + '    properties : ' )
				+ nullif (
			  char(10) + '    timeout    : ' + str(nullif(job_default_timeout,0), @max_timeout),
			  char(10) + '    timeout    : ' ) +
			  char(10)
		    from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		end
		else -- vc_conv = 1
		begin
		    select	'job_id: ' + str(job_id, @max_id) + '  name: ''' + convert(varchar(64), job_name) + ''''
			+ char(10) + '    description: ' + convert(varchar(128), job_description)
			+ char(10) + '    owner      : ' + job_owner
			+ char(10) + '    created    : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties : ' + job_uproperties,
			  char(10) + '    properties : ' )
				+ nullif (
			  char(10) + '    timeout    : ' + str(nullif(job_default_timeout,0), @max_timeout),
			  char(10) + '    timeout    : ' ) +
			  char(10)
		    from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		end
		
		select  @max_id=max(char_length(convert(varchar(16), sched_id))),
			@max_interval=max(char_length(convert(varchar(16), sched_interval)))
		from sybmgmtdb..js_schedules where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_sched_id = js_schedules.sched_id) and
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val)
		select @err=@@error, @rows=@@rowcount

		if @vc_conv = 0
		begin
		    select	'sched_id: ' + str(sched_id, @max_id) + '  name: ''' + sched_name + ''''
			+ char(10) + '    description: ' + sched_description
			+ char(10) + '    owner      : ' + sched_owner
			+ char(10) + '    created    : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties : ' + sched_uproperties,
			  char(10) + '    properties : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating  : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating  : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating  : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate  : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate  : ' ) +
				nullif (
			  char(10) + '    enddate    : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate    : ' ) +
			  char(10)
		    from sybmgmtdb..js_schedules where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_sched_id = js_schedules.sched_id) and
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
			  or (@owner_arg = 1 and  sched_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    if @list_val = 'unscheduled' return @err
		end
		else -- @vc_conv = 1
		begin
		    select	'sched_id: ' + str(sched_id, @max_id) + '  name: ''' + convert(varchar(64), sched_name) + ''''
			+ char(10) + '    description: ' + convert(varchar(128), sched_description)
			+ char(10) + '    owner      : ' + sched_owner
			+ char(10) + '    created    : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties : ' + sched_uproperties,
			  char(10) + '    properties : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating  : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating  : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating  : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate  : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate  : ' ) +
				nullif (
			  char(10) + '    enddate    : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate    : ' ) +
			  char(10)
		    from sybmgmtdb..js_schedules where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_sched_id = js_schedules.sched_id) and
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
			  or (@owner_arg = 1 and  sched_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		    if @list_val = 'unscheduled' return @err
		end -- @vc_conv = 1
		end
	end
	--
	-- Report / list any job and schedules which are unscheduled or bound to
	-- scheduledjobs that are not shared_run
	--
	if @list_val is NULL
	begin
		if @list = 'list'
		begin
		    if @vc_conv = 0
		    begin
			select  job_id=job_id,		job_name=job_name,
				job_description=job_description,
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout
			from sybmgmtdb..js_jobs where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_job_id = js_jobs.job_id and
					(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
						or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
					(@all_arg = 1
			  		or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  		or (@owner_arg = 1 and  sjob_owner = @owner_val)
					)
				) and
				(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
				(@all_arg = 1
				  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
				  or (@owner_arg = 1 and  job_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount

			select	sched_id=sched_id,	sched_name=sched_name,
				sched_description=sched_description,
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates
			from sybmgmtdb..js_schedules where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_sched_id = js_schedules.sched_id and
					(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
						or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
					(@all_arg = 1
			  		or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  		or (@owner_arg = 1 and  sjob_owner = @owner_val)
					)
				) and
				(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
				  or (@owner_arg = 1 and  sched_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		    else -- @vc_conv != 0
		    begin
			select  job_id=job_id,		job_name=convert(varchar(64), job_name),
				job_description=convert(varchar(128), job_description),
				job_owner=job_owner,	job_created=job_created,
				job_properties=job_uproperties,
				job_default_timeout=job_default_timeout
			from sybmgmtdb..js_jobs where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_job_id = js_jobs.job_id and
					(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
						or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
					(@all_arg = 1
			  		or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  		or (@owner_arg = 1 and  sjob_owner = @owner_val)
					)
				) and
				(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
				(@all_arg = 1
				  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
				  or (@owner_arg = 1 and  job_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount

			select	sched_id=sched_id,	sched_name=convert(varchar(64), sched_name),
				sched_description=convert(varchar(128), sched_description),
				sched_owner=sched_owner,	sched_created=sched_created, 
				sched_properties=sched_uproperties,
				sched_interval=sched_uinterval,
				sched_startdate=sched_startdate, sched_starttime=sched_starttime,
				sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
				sched_days=sched_udays,		sched_dates=sched_udates
			from sybmgmtdb..js_schedules where
				not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
					js_scheduledjobs.sjob_sched_id = js_schedules.sched_id and
					(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
						or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
					(@all_arg = 1
			  		or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  		or (@owner_arg = 1 and  sjob_owner = @owner_val)
					)
				) and
				(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
				(@all_arg = 1
				  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
				  or (@owner_arg = 1 and  sched_owner = @owner_val)
				)
			select @err=@@error, @rows=@@rowcount
			return @err
		    end
		end
		--
		-- report
		--
		select  @max_id=max(char_length(convert(varchar(16), job_id))),
			@max_timeout=max(char_length(convert(varchar(16), job_default_timeout)))
		from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			) and
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount

		if @vc_conv = 0
		begin
		    select	'job_id: ' + str(job_id, @max_id) + '  name: ''' + job_name + ''''
			+ char(10) + '    description: ' + job_description
			+ char(10) + '    owner      : ' + job_owner
			+ char(10) + '    created    : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties : ' + job_uproperties,
			  char(10) + '    properties : ' )
				+ nullif (
			  char(10) + '    timeout    : ' + str(nullif(job_default_timeout,0), @max_timeout),
			  char(10) + '    timeout    : ' ) +
			  char(10)
		    from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			) and
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		end
		else -- @vc_conv != 0
		begin
		    select	'job_id: ' + str(job_id, @max_id) + '  name: ''' + convert(varchar(64), job_name) + ''''
			+ char(10) + '    description: ' + convert(varchar(128), job_description)
			+ char(10) + '    owner      : ' + job_owner
			+ char(10) + '    created    : ' + convert(varchar(64), job_created)
				+ nullif (
			  char(10) + '    properties : ' + job_uproperties,
			  char(10) + '    properties : ' )
				+ nullif (
			  char(10) + '    timeout    : ' + str(nullif(job_default_timeout,0), @max_timeout),
			  char(10) + '    timeout    : ' ) +
			  char(10)
		    from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			) and
			(@job_id  = -1 or job_id = @job_id or job_name = @jname_val)    and
			(@all_arg = 1
			  or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)))
			  or (@owner_arg = 1 and  job_owner = @owner_val)
			)
		end
		
		select  @max_id=max(char_length(convert(varchar(16), sched_id))),
			@max_interval=max(char_length(convert(varchar(16), sched_interval)))
		from sybmgmtdb..js_schedules where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_sched_id = js_schedules.sched_id and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			) and
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val)
		select @err=@@error, @rows=@@rowcount

		if @vc_conv = 0
		begin
		    select	'sched_id: ' + str(sched_id, @max_id) + '  name: ''' + sched_name + ''''
			+ char(10) + '    description: ' + sched_description
			+ char(10) + '    owner      : ' + sched_owner
			+ char(10) + '    created    : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties : ' + sched_uproperties,
			  char(10) + '    properties : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating  : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating  : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating  : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate  : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate  : ' ) +
				nullif (
			  char(10) + '    enddate    : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate    : ' ) +
			  char(10)
		    from sybmgmtdb..js_schedules where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_sched_id = js_schedules.sched_id and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			) and
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
			  or (@owner_arg = 1 and  sched_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		end
		else
		begin
		    select	'sched_id: ' + str(sched_id, @max_id) + '  name: ''' + convert(varchar(64), sched_name) + ''''
			+ char(10) + '    description: ' + convert(varchar(128), sched_description)
			+ char(10) + '    owner      : ' + sched_owner
			+ char(10) + '    created    : ' + convert(varchar(64), sched_created)
				+ nullif (
			  char(10) + '    properties : ' + sched_uproperties,
			  char(10) + '    properties : ' )
			+ ( case
				-- No interval:- can be on days or dates, with a starttime, and a start / end date.
				when sched_interval_units = ' '
				then
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- daily schedule:- on days, on dates and endtime have no meaning.
				when sched_interval_units = 'd'
				then
			  char(10) + '    repeating  : ' + 
				substring('every day', 1 - abs(sign(sched_interval - 1)), 9) +
				substring('every ' + str(sched_interval, @max_interval) + ' days',
					abs(sign(sched_interval - 1)), 6+@max_interval+5) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' )

				-- hours
				when sched_interval_units = 'h'
				then
			  char(10) + '    repeating  : ' +
				substring('every hour', 1 - abs(sign(sched_interval - 1)), 10) +
				substring('every ' + str(sched_interval, @max_interval) + ' hours',
					abs(sign(sched_interval - 1)), 6+@max_interval+6) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				-- minutes
				when sched_interval_units = 'm'
				then
			  char(10) + '    repeating  : ' +
				substring('every minute', 1 - abs(sign(sched_interval - 1)), 12) +
				substring('every ' + str(sched_interval, @max_interval) + ' minutes',
					abs(sign(sched_interval - 1)), 6+@max_interval+8) +
				nullif (
			  char(10) + '    starttime  : ' + substring(convert(varchar(16), sched_starttime, 8), 1, 5),
			  char(10) + '    starttime  : ' ) +
				nullif (
			  char(10) + '    endtime    : ' + substring(convert(varchar(16), sched_endtime, 8), 1, 5),
			  char(10) + '    endtime    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udays,
			  char(10) + '    on days    : ' ) +
				nullif (
			  char(10) + '    on days    : ' + sched_udates,
			  char(10) + '    on days    : ' )

				else NULL
			end ) +
				nullif (
			  char(10) + '    startdate  : ' + convert(varchar(16), sched_startdate, 106),
			  char(10) + '    startdate  : ' ) +
				nullif (
			  char(10) + '    enddate    : ' + convert(varchar(16), sched_enddate, 106),
			  char(10) + '    enddate    : ' ) +
			  char(10)
		    from sybmgmtdb..js_schedules where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_sched_id = js_schedules.sched_id and
				(@id_arg = 0 or sjob_id = @sjob_id or sjob_job_id = @job_id
					or sjob_sched_id = @sched_id or sjob_name = @sjname_val) and
				(@all_arg = 1
			  	or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)))
			  	or (@owner_arg = 1 and  sjob_owner = @owner_val)
				)
			) and
			(@sched_id = -1 or sched_id = @sched_id or sched_name = @sname_val) and
			(@all_arg = 1
			  or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)))
			  or (@owner_arg = 1 and  sched_owner = @owner_val)
			)
		    select @err=@@error, @rows=@@rowcount
		end
		return @err
	end
	return 0

end
go
if exists (select name from sysobjects where name = 'sp_sjobhelp')
begin
	print 'Created sp_sjobhelp'
	grant execute on sp_sjobhelp to js_user_role
	grant execute on sp_sjobhelp to js_admin_role
	grant execute on sp_sjobhelp to js_client_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_sjobhistory')
	drop proc sp_sjobhistory
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobhistory  @name univarchar()  @option univarchar()
--
--      @name is the name or id of a scheduled job, a job or runid.
--      The selection is made by using a prefix of sjname=, jname= or runid=.
--      With no prefix the default is the name or id of a scheduled job.
--      Example:-
--              'sjname=scheduled_job_name_or_id'
--              'jname=job_name_or_id'
--              'runid=23678'
--
--      @option is a list of control options to the procedure which specify
--      whether the action is to list or to drop and to restrict the scope of
--      the action within the history and output tables.
--
--      options, such as minsize or age may be supplied to control the scope.
--      For example:
--              @name='sjname=scheduled_job_name_or_id', @option='age=30'
--              @name=NULL, @option='drop,minsize=10000'
--              @name='runid=23678'
--
--      Valid options for the action are:
--          'list', 'list_short', 'list_output', 'drop', 'drop_output'
--      Valid options to restrict the scope are:
--          'all_users', 'force', 'owner', 'user', 'age' and 'minsize'.
--
--      The 'force' option does not check for running jobs.
--      The 'all_users', 'owner' and 'user' options are only available to
--      callers with js_admin_role role.
--
create proc sp_sjobhistory (
	@name		univarchar(128)	= NULL,
	@option		univarchar(512)	= NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(128), @opt_name univarchar(32), @opt_value univarchar(96)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(128), @vc_conv int
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int
	declare @err int, @rows int, @msgno int, @is_admin int, @job_id int, @run_id int, @sjob_id int
	declare @owner_arg int, @user_arg int, @all_arg int, @id_arg int, @sjob_name univarchar(64), @force int
	declare @cmd_val varchar(32), @job_name univarchar(64), @owner_name varchar(32), @user_name varchar(32)
	declare @age_val datetime, @age_arg int, @size_val int, @size_arg int, @state char(2)
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobhistory'
	select	@owner_arg=0, @user_arg=0, @age_arg=0, @size_arg=0, @all_arg=0, @id_arg=0, @force=0, @vc_conv=1
	select  @cmd_val='list', @run_id=-1, @sjob_id=-1, @job_name=NULL

	select @is_admin=proc_role('js_admin_role')
	select @value=ltrim(rtrim(@option))
	--
	-- Get and validate the name or id of the scheduled job, job or runnid.
	--
	select @opt_val_pair = ltrim(rtrim(@name))
	if @name is not NULL
	begin
		select @eq_pos=patindex('%=%', @opt_val_pair), @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		if @eq_pos <= 0				-- no prefix, defaults to scheduled job
			select @opt_name='sjname', @opt_value=@opt_val_pair
		else if @eq_pos = @opt_val_len		-- opt_name=  error
		begin
			-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
                	select @vcbuf1=@opt_val_pair
			raiserror 19098, @sp_name, @vcbuf1
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))
			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value = ltrim(rtrim(@opt_value))
		end
	end
	else	select @opt_name=NULL
	--
	if @opt_name = 'sjname'
	begin
		-- the name or id of a scheduled job
		--
		-- if it's an id just use it, do not check if the sjob_id exists as it may
		-- have been deleted.  Otherwise lookup the sjob_id for the given name.
        		if substring(@opt_value, 1, 1) like '[0-9]'
			exec @sjob_id=sp_js_check_id @name_id=@opt_value, @cmd=1
		else
			exec @sjob_id=sp_js_check_id @name_id=@opt_value, @cmd=0, @table='sjob', @return_id=1, @is_admin=@is_admin
		-- if the name is non-unique, we add a subquery to match on name, but just on list, not drop
		if @sjob_id = -19097
		begin
			select @id_arg=1, @run_id=-1, @job_name=NULL, @sjob_id=-1, @sjob_name=@opt_value
		end
		else if @sjob_id < 0
		begin
			select @msgno = abs(@sjob_id), @vcbuf1=@opt_name
			raiserror @msgno, @sp_name, @vcbuf1
			return -@@error
		end
		else select @id_arg=1, @run_id=-1, @job_name=NULL, @sjob_name=NULL
	end
	else if @opt_name = 'jname'
	begin
		-- the name or id of a job
		--
		-- if it's a job name just use it, otherwise check the job id
		-- and then lookup the job name
		--
        		if substring(@opt_value, 1, 1) not like '[0-9]'
		begin
			-- do not check the job_name exists in js_jobs as it may have been deleted.
			select @id_arg=1, @job_name=@opt_value, @sjob_id=-1, @run_id=-1, @sjob_name=NULL
		end
		else
		begin
			exec @job_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='job', @return_id=1, @is_admin=@is_admin
			if @job_id < 0
			begin
				select @msgno = abs(@job_id), @vcbuf1=@opt_name
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @job_name=job_name from sybmgmtdb..js_jobs where job_id=@job_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_jobs', @err
				return -@@error
			end
			select @id_arg=1, @sjob_id=-1, @run_id=-1, @sjob_name=NULL
		end
	end
	else if @opt_name = 'runid'
	begin
		exec @run_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='jsh', @is_admin=@is_admin
		if @run_id < 0
		begin
			select @msgno = abs(@run_id), @vcbuf1=@opt_name
			raiserror @msgno, @sp_name, @vcbuf1
			return -@@error
		end
		select @id_arg=1, @job_name=NULL, @sjob_id=-1, @sjob_name=NULL
	end
	else if @opt_name is not NULL
	begin
		-- 19098 'Procedure %1!, @name=''%2!'', the name or id is missing or invalid.'
		select @vcname=@name
		raiserror 19098, @sp_name, @vcname
		return -@@error
	end
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0					-- @option=opt_name
		begin
			select @opt_name=ltrim(rtrim(@opt_val_pair))
			if @opt_name = 'list' or @opt_name = 'list_output' or @opt_name = 'list_short'
					or @opt_name = 'drop' or @opt_name = 'drop_output'
			begin
				select @cmd_val=@opt_name
			end
			else if @opt_name = 'force'	select @force=1
			else if @opt_name = 'all' or @opt_name = 'all_users'
			begin
				if @is_admin = 0
				begin
					-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
					raiserror 19077, @sp_name
					return -@@error
				end
				select @all_arg=1
			end
			else
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_val_pair
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			select @curpos=@end_pos + 1
			continue
		end
		else if @eq_pos = @opt_val_len			-- @property=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len - @eq_pos)
			select @opt_value=ltrim(rtrim(@opt_value))
		end

		if @opt_name = 'sjname'
		begin
			-- the name or id of a scheduled job
			--
			-- if it's an id just use it, do not check if the sjob_id exists as it may
			-- have been deleted.  Otherwise lookup the sjob_id for the given name.
        		if substring(@opt_value, 1, 1) like '[0-9]'
				exec @sjob_id=sp_js_check_id @name_id=@opt_value, @cmd=1
			else
				exec @sjob_id=sp_js_check_id @name_id=@opt_value, @cmd=0, @table='sjob', @return_id=1, @is_admin=@is_admin
			-- if the name is non-unique, we add a subquery to match on name, but just on list, not drop
			if @sjob_id = -19097
			begin
				select @id_arg=1, @run_id=-1, @job_name=NULL, @sjob_id=-1, @sjob_name=@opt_value
			end
			else if @sjob_id < 0
			begin
				select @msgno = abs(@sjob_id), @vcbuf1=@opt_name
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			else select @id_arg=1, @run_id=-1, @job_name=NULL, @sjob_name=NULL
		end
		else if @opt_name = 'jname'
		begin
			-- the name or id of a job
			--
			-- if it's a job name just use it, otherwise check the job id
			-- and then lookup the job name
			--
        		if substring(@opt_value, 1, 1) not like '[0-9]'
			begin
				-- do not check the job_name exists in js_jobs as it may have been deleted.
				select @id_arg=1, @job_name=@opt_value, @sjob_id=-1, @run_id=-1, @sjob_name=NULL
			end
			else
			begin
				exec @job_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='job', @return_id=1, @is_admin=@is_admin
				if @job_id < 0
				begin
					select @msgno = abs(@job_id), @vcbuf1=@opt_name
					raiserror @msgno, @sp_name, @vcbuf1
					return -@@error
				end
				select @job_name=job_name from sybmgmtdb..js_jobs where job_id=@job_id
				select @err=@@error, @rows=@@rowcount
				if @err != 0
				begin
					-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
					raiserror 19076, @sp_name, 'js_jobs', @err
					return -@@error
				end
				select @id_arg=1, @sjob_id=-1, @run_id=-1, @sjob_name=NULL
			end
		end
		else if @opt_name = 'runid'
		begin
			exec @run_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='jsh', @is_admin=@is_admin
			if @run_id < 0
			begin
				select @msgno = abs(@run_id), @vcbuf1=@opt_name
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @id_arg=1, @job_name=NULL, @sjob_id=-1, @sjob_name=NULL
		end
		else if @opt_name = 'user' or @opt_name = 'owner'
		begin
			if @opt_name = 'user'
				select @user_name=@opt_value, @user_arg=1
			else	select @owner_name=@opt_value, @owner_arg=1
			--
			-- Must be js_admin_role or name is the caller
			--
			if @is_admin=0 and suser_name() != @opt_value
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			-- We do not check the user name is valid, this is to allow for
			-- tidying up after a user has been deleted.
		end
		else if @opt_name = 'age' or @opt_name = 'minsize'
		begin
			exec @err=sp_js_check_id @name_id=@opt_value, @cmd=3
			if @err < 0
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_name
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			if @opt_name = 'age'
			begin
				select @err=0-@err
				select @age_val=dateadd(day, @err, getdate()), @age_arg=1
			end
			else	select @size_val=@err, @size_arg=1
		end
		else if @opt_name = 'sp_name'
		begin
			if      @opt_value = 'sp_dropjobhistory'	select @cmd_val='gui_drop'
			else if @opt_value = 'sp_dropjoboutput'		select @cmd_val='gui_drop_output'
			else if @opt_value = 'sp_listjobhistory'	select @cmd_val='gui_list'
			else
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_name
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			select @sp_name=@opt_name
		end
		else if @opt_name = 'list'
		begin
			if      @opt_value = 'short'	select @cmd_val='gui_list_short'
			else if @opt_value = 'full'	select @cmd_val='gui_list_full'
			else if @opt_value = 'count'	select @cmd_val='gui_list_count'
			else if @opt_value = 'running'	select @cmd_val='gui_list_running'
			else
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_name
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @opt_name = 'varchar' or @opt_name = 'ascii'	select @vc_conv=1
		else if @opt_name = 'unichar' or @opt_name = 'utf8'	select @vc_conv=0
		else
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		select @curpos=@end_pos + 1
	end
	--
	-- drop history and or output
	--
	if @cmd_val = 'drop' or @cmd_val = 'drop_output' or @cmd_val = 'gui_drop' or @cmd_val = 'gui_drop_output'
	begin
		-- reject if sjob_name was not unique
		if @sjob_name is not NULL
		begin
			select @vcname=@sjob_name
			raiserror 19097, @sp_name, @vcname
			return -@@error
		end
		--
		-- reject if all arguments are NULL
		--
		if @id_arg = 0 and @owner_arg = 0 and @user_arg = 0 and @age_arg = 0 and @size_arg = 0
		begin
			-- 19085 'Procedure %1!, all the arguments are NULL, at least one must be supplied.'
			raiserror 19085, @sp_name
			return -@@error
		end
		--
		-- Silently ignore jobs that are running, unless runid was supplied
		--
		if @run_id != -1
		begin
			-- When an admin user supplies an id, we do not add a filter on user name
			--
			if @is_admin = 0
			begin
				select @user_name=suser_name(), @user_arg=1
			end
			else
			begin
				-- If an admin user has not supplied a user name, owner or all_users
				-- check the ownership
				if @user_arg = 0 and @owner_arg = 0 and @all_arg = 0
				begin
					exec @run_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='jsh', @is_admin=0
					if @run_id < 0
					begin
						select @msgno = abs(@run_id), @vcbuf1=@opt_name
						raiserror @msgno, @sp_name, @vcbuf1
						return -@@error
					end
				end
			end

			select @state=jsh_state from sybmgmtdb..js_history
				where jsh_exid=@run_id and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@owner_arg  =0 or jsh_user_run = @owner_name) and
				(@age_arg    =0 or jsh_jobstart < @age_val)    and
				(@size_arg   =0 or jsh_size     > @size_val)
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_history', @err
				return -@@error
			end
			if @rows = 0
			begin
				if @cmd_val = 'gui_drop' or @cmd_val = 'gui_drop_output'
					select 0
				return 0
			end
			--
			-- force removes the state check and always allows history to be deleted
			--
			if @force = 0 and ( @state like '[QR]%' or @state like '[CTX]1' )
			begin
				-- 19072 'Procedure %1!, unable to perform the operation while running jobs are using %2!.'
				raiserror 19072, @sp_name, @run_id
				return -@@error
			end
			--
			-- We have already selected with any of the other clauses, so just delete on run_id
			--
			begin tran sp_sjobhistory1
			save tran nested_tran
			delete from sybmgmtdb..js_output where jsout_exid = @run_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19073 'Procedure %1!, failed to delete an entry in the %2! table, delete error %3!.'
				raiserror 19073, @sp_name, 'js_output', @err
				return -@@error
			end
			if @cmd_val = 'drop' or @cmd_val = 'gui_drop'
			begin
				delete from sybmgmtdb..js_history where jsh_exid = @run_id
				select @err=@@error, @rows=@@rowcount
				if @err != 0
				begin
					rollback tran nested_tran
					commit tran
					-- 19073 'Procedure %1!, failed to delete an entry in the %2! table, delete error %3!.'
					raiserror 19073, @sp_name, 'js_history', @err
					return -@@error
				end
			end
			else
			begin
				update sybmgmtdb..js_history set jsh_size = 0 where jsh_exid = @run_id
				select @err=@@error, @rows=@@rowcount
				if @err != 0
				begin
					rollback tran nested_tran
					commit tran
					-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
					raiserror 19074, @sp_name, 'js_history', @err
					return -@@error
				end
			end
			commit tran
			if @cmd_val = 'gui_drop' or @cmd_val = 'gui_drop_output'
				select @rows
			return 0
		end
		--
		-- If the all option hasn't been given and there isn't a filter
		-- on user or owner, then we add one for the caller.
		--
		if @all_arg = 0 and @user_arg = 0 and @owner_arg = 0
			select @user_name=suser_name(), @user_arg=1
		--
		-- First delete the js_output then the history
		--
		-- There is a small window between these two, when a job could run after
		-- deleting from js_output and complete before deleting the history.
		-- This could lead to orphans in the js_output table.
		-- We could update lock the history on @@spid, then delete output and
		-- history for those entries.
		begin tran sp_sjobhistory2
		save tran nested_tran
		if @cmd_val = 'drop' or @cmd_val = 'gui_drop'
		begin
			update sybmgmtdb..js_history set jsh_update = @@spid
			from sybmgmtdb..js_history readpast
			where	(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)       and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@owner_arg  =0 or jsh_user_run = @owner_name) and
				(@age_arg    =0 or jsh_jobstart < @age_val)    and
				(@size_arg   =0 or jsh_size     > @size_val)   and
				(@force = 1 or (jsh_state not like '[QR]%' and jsh_state not like '[CTX]1'))
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, delete error %3!.'
				raiserror 19074, @sp_name, 'js_history', @err
				return -@@error
			end
		end
		delete sybmgmtdb..js_output from sybmgmtdb..js_output readpast, sybmgmtdb..js_history readpast
			where jsout_exid = jsh_exid and jsh_update = @@spid
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19073 'Procedure %1!, failed to delete an entry in the %2! table, delete error %3!.'
			raiserror 19073, @sp_name, 'js_output', @err
			return -@@error
		end
		if @cmd_val = 'drop' or @cmd_val = 'gui_drop'
		begin
			delete sybmgmtdb..js_history from sybmgmtdb..js_history readpast where jsh_update = @@spid
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19073 'Procedure %1!, failed to delete an entry in the %2! table, delete error %3!.'
				raiserror 19073, @sp_name, 'js_history', @err
				return -@@error
			end
		end
		else
		begin
			update sybmgmtdb..js_history set jsh_size=0, jsh_update=0
				from sybmgmtdb..js_history readpast where jsh_update = @@spid
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_history', @err
				return -@@error
			end
		end
		commit tran
		if @cmd_val = 'gui_drop' or @cmd_val = 'gui_drop_output'
			select @rows
		return 0
	end
	--
	-- If the all option hasn't been given and there isn't a filter
	-- on user or owner, then add one for the caller
	--
	if @all_arg = 0 and @user_arg = 0 and @owner_arg = 0
		select @user_name=suser_name(), @user_arg=1

	if @cmd_val = 'gui_list' or @cmd_val = 'gui_list_short'
		or @cmd_val = 'gui_list_full' or @cmd_val = 'gui_list_count'
		or @cmd_val = 'gui_list_running'
	begin
		-- the GUI list commands do not need order by clauses
		if @cmd_val = 'gui_list_count'
		begin
			select	@msgno=count(jsh_exid) 
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)           and
				(@user_arg   =0 or jsh_user_req = @user_name)      and
				(@owner_arg  =0 or jsh_user_run = @owner_name)     and
				(@age_arg    =0 or jsh_jobstart < @age_val)        and
				(@size_arg   =0 or jsh_size     > @size_val)
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_history / js_scheduledjobs', @err
				return -@@error
			end
			select @msgno
			return 0
		end
		if @cmd_val = 'gui_list_short'
		begin
			select	job_start=jsh_jobstart,	sjob_id=jsh_sjobid,
				job_name=jsh_jobname,	sched_name=jsh_schedname,
				job_state=jsh_state,	job_user_run=jsh_user_run,
				job_server=sjob_server,	job_size=jsh_size, job_spid=jsh_spid
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)           and
				(@user_arg   =0 or jsh_user_req = @user_name)      and
				(@owner_arg  =0 or jsh_user_run = @owner_name)     and
				(@age_arg    =0 or jsh_jobstart < @age_val)        and
				(@size_arg   =0 or jsh_size     > @size_val)
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_history / js_scheduledjobs', @err
				return -@@error
			end
			return @err
		end
		if @cmd_val = 'gui_list_full' or @cmd_val = 'gui_list'
		begin
			select	job_run_id=jsh_exid,		sjob_id=jsh_sjobid,
				job_name=jsh_jobname,		sched_name=jsh_schedname,
				job_state=jsh_state,
				job_start=jsh_jobstart,		job_end=jsh_jobend,
				job_exit_code=jsh_exit_code,	job_user_code=jsh_user_code,
				job_atat_error=jsh_atat_error,	job_os_code=jsh_os_code,
				job_user_run=jsh_user_run,	job_user_req=jsh_user_req,
				job_short_message=jsh_smsg,	job_long_message=jsh_lmsg,
				job_size=jsh_size,
				job_server=sjob_server,		job_spid=jsh_spid
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)       and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@owner_arg  =0 or jsh_user_run = @owner_name) and
				(@age_arg    =0 or jsh_jobstart < @age_val)    and
				(@size_arg   =0 or jsh_size     > @size_val)
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_history', @err
				return -@@error
			end
			return @err
		end
		--
		-- @cmd_val = 'gui_list_running'
		--
			select	job_run_id=jsh_exid,		sjob_id=jsh_sjobid,
				job_name=jsh_jobname,		sched_name=jsh_schedname,
				job_state=jsh_state,
				job_start=jsh_jobstart,		job_end=jsh_jobend,
				job_exit_code=jsh_exit_code,	job_user_code=jsh_user_code,
				job_atat_error=jsh_atat_error,	job_os_code=jsh_os_code,
				job_user_run=jsh_user_run,	job_user_req=jsh_user_req,
				job_short_message=jsh_smsg,	job_long_message=jsh_lmsg,
				job_size=jsh_size,
				job_server=sjob_server,		job_spid=jsh_spid
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)       and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@owner_arg  =0 or jsh_user_run = @owner_name)
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_history', @err
				return -@@error
			end
			return @err
	end
	--
	--
	if @cmd_val = 'list_short'
	begin
		if @sjob_name is not NULL
		begin
		    if @vc_conv = 0
		    begin
			select	sjob_id=jsh_sjobid,
				sjob_jobname=jsh_jobname,	sjob_schedname=jsh_schedname,
				sjob_state=jsh_state,		sjob_start=jsh_jobstart,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
							where sjob_name = @sjob_name)) and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select	sjob_id=jsh_sjobid,
				sjob_jobname=convert(varchar(64), jsh_jobname),
				sjob_schedname=convert(varchar(64), jsh_schedname),
				sjob_state=jsh_state,		sjob_start=jsh_jobstart,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
							where sjob_name = @sjob_name)) and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		end
		else
		begin
		    if @vc_conv = 0
		    begin
			select	sjob_id=jsh_sjobid,
				sjob_jobname=jsh_jobname,	sjob_schedname=jsh_schedname,
				sjob_state=jsh_state,		sjob_start=jsh_jobstart,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)            and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select	sjob_id=jsh_sjobid,
				sjob_jobname=convert(varchar(64), jsh_jobname),
				sjob_schedname=convert(varchar(64), jsh_schedname),
				sjob_state=jsh_state,		sjob_start=jsh_jobstart,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)            and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		end
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_history / js_scheduledjobs', @err
			return -@@error
		end
		return @err
	end
	if @cmd_val = 'list'
	begin
		if @sjob_name is not NULL
		begin
		    if @vc_conv = 0
		    begin
			select	sjob_run_id=jsh_exid,		sjob_id=jsh_sjobid,
				sjob_jobname=jsh_jobname,	sjob_schedname=jsh_schedname,
				sjob_state=jsh_state, sjob_start=jsh_jobstart,	sjob_end=jsh_jobend,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_exit_code=jsh_exit_code,	sjob_user_code=jsh_user_code,
				sjob_atat_error=jsh_atat_error,	sjob_os_code=jsh_os_code,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_short_message=jsh_smsg,	sjob_long_message=jsh_lmsg,
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
							where sjob_name = @sjob_name)) and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select	sjob_run_id=jsh_exid,		sjob_id=jsh_sjobid,
				sjob_jobname=convert(varchar(64), jsh_jobname),
				sjob_schedname=convert(varchar(64), jsh_schedname),
				sjob_state=jsh_state, sjob_start=jsh_jobstart,	sjob_end=jsh_jobend,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_exit_code=jsh_exit_code,	sjob_user_code=jsh_user_code,
				sjob_atat_error=jsh_atat_error,	sjob_os_code=jsh_os_code,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_short_message=convert(varchar(64), jsh_smsg),
				sjob_long_message=convert(varchar(255), jsh_lmsg),
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
							where sjob_name = @sjob_name)) and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		end
		else
		begin
		    if @vc_conv = 0
		    begin
			select	sjob_run_id=jsh_exid,		sjob_id=jsh_sjobid,
				sjob_jobname=jsh_jobname,	sjob_schedname=jsh_schedname,
				sjob_state=jsh_state, sjob_start=jsh_jobstart,	sjob_end=jsh_jobend,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_exit_code=jsh_exit_code,	sjob_user_code=jsh_user_code,
				sjob_atat_error=jsh_atat_error,	sjob_os_code=jsh_os_code,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_short_message=jsh_smsg,	sjob_long_message=jsh_lmsg,
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)            and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select	sjob_run_id=jsh_exid,		sjob_id=jsh_sjobid,
				sjob_jobname=convert(varchar(64), jsh_jobname),
				sjob_schedname=convert(varchar(64), jsh_schedname),
				sjob_state=jsh_state, sjob_start=jsh_jobstart,	sjob_end=jsh_jobend,
				sjob_server=sjob_server,	sjob_spid=jsh_spid,
				sjob_exit_code=jsh_exit_code,	sjob_user_code=jsh_user_code,
				sjob_atat_error=jsh_atat_error,	sjob_os_code=jsh_os_code,
				sjob_user_run=jsh_user_run,	sjob_user_req=jsh_user_req,
				sjob_short_message=convert(varchar(64), jsh_smsg),
				sjob_long_message=convert(varchar(255), jsh_lmsg),
				sjob_size=jsh_size
			from sybmgmtdb..js_history readpast, sybmgmtdb..js_scheduledjobs readpast
			where	(js_history.jsh_sjobid *= js_scheduledjobs.sjob_id) and
				(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)            and
				(@owner_arg  =0 or jsh_user_run = @owner_name)      and
				(@user_arg   =0 or jsh_user_req = @user_name)       and
				(@age_arg    =0 or jsh_jobstart < @age_val)         and
				(@size_arg   =0 or jsh_size     > @size_val)
			order by jsh_jobstart desc
			select @err=@@error, @rows=@@rowcount
		    end
		end
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_history / js_scheduledjobs', @err
			return -@@error
		end
		return @err
	end
	if @cmd_val = 'list_output'
	begin
		if @sjob_name is not NULL
		begin
		    if @vc_conv = 0
		    begin
			select	jsout_run_id=jsout_exid, jsout_seqno=jsout_seqno,
				jsout_size=jsout_size,	
				jsout_text=substring(jsout_text, 1, isnull(char_length(jsout_text),1)-1)
			from sybmgmtdb..js_output readpast where jsout_exid in
			(select jsh_exid from sybmgmtdb..js_history readpast
			where	(jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
						where sjob_name = @sjob_name)) and
				(@owner_arg  =0 or jsh_user_run = @owner_name) and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@age_arg    =0 or jsh_jobstart < @age_val)    and
				(@size_arg   =0 or jsh_size     > @size_val)
			)
			order by jsout_exid, jsout_seqno
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select	jsout_run_id=jsout_exid, jsout_seqno=jsout_seqno,
				jsout_size=jsout_size,	
				jsout_text=convert(varchar(1800), substring(jsout_text, 1, isnull(char_length(jsout_text),1)-1))
			from sybmgmtdb..js_output readpast where jsout_exid in
			(select jsh_exid from sybmgmtdb..js_history readpast
			where	(jsh_sjobid in (select sjob_id from sybmgmtdb..js_scheduledjobs
						where sjob_name = @sjob_name)) and
				(@owner_arg  =0 or jsh_user_run = @owner_name) and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@age_arg    =0 or jsh_jobstart < @age_val)    and
				(@size_arg   =0 or jsh_size     > @size_val)
			)
			order by jsout_exid, jsout_seqno
			select @err=@@error, @rows=@@rowcount
		    end
		end
		else
		begin
		    if @vc_conv = 0
		    begin
			select	jsout_run_id=jsout_exid, jsout_seqno=jsout_seqno,
				jsout_size=jsout_size,	
				jsout_text=substring(jsout_text, 1, isnull(char_length(jsout_text),1)-1)
			from sybmgmtdb..js_output readpast where jsout_exid in
			(select jsh_exid from sybmgmtdb..js_history readpast
			where	(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)       and
				(@owner_arg  =0 or jsh_user_run = @owner_name) and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@age_arg    =0 or jsh_jobstart < @age_val)    and
				(@size_arg   =0 or jsh_size     > @size_val)
			)
			order by jsout_exid, jsout_seqno
			select @err=@@error, @rows=@@rowcount
		    end
		    else
		    begin
			select	jsout_run_id=jsout_exid, jsout_seqno=jsout_seqno,
				jsout_size=jsout_size,	
				jsout_text=convert(varchar(1800), substring(jsout_text, 1, isnull(char_length(jsout_text),1)-1))
			from sybmgmtdb..js_output readpast where jsout_exid in
			(select jsh_exid from sybmgmtdb..js_history readpast
			where	(@id_arg = 0 or jsh_exid = @run_id or
						jsh_sjobid = @sjob_id or
						jsh_jobname = @job_name)       and
				(@owner_arg  =0 or jsh_user_run = @owner_name) and
				(@user_arg   =0 or jsh_user_req = @user_name)  and
				(@age_arg    =0 or jsh_jobstart < @age_val)    and
				(@size_arg   =0 or jsh_size     > @size_val)
			)
			order by jsout_exid, jsout_seqno
			select @err=@@error, @rows=@@rowcount
		    end
		end
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_output / js_history', @err
			return -@@error
		end
		return @err
	end

	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobhistory')
begin
	print 'Created sp_sjobhistory'
	grant execute on sp_sjobhistory to js_user_role
	grant execute on sp_sjobhistory to js_client_role
	grant execute on sp_sjobhistory to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_modifyscheduledjob')
	drop proc sp_modifyscheduledjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_modifyscheduledjob (
	@sjname_id	univarchar(64)	= NULL,
	@jname_id	univarchar(64)	= NULL,
	@sjname		univarchar(64)	= NULL,
	@enable		int		= NULL,
	@sjproperties	varchar(128)	= NULL,
	@server		varchar(30)	= NULL,
	@locale		varchar(30)	= NULL,
	@sjowner	varchar(30)	= NULL,
	@timeout	int		= NULL,
	@jname		univarchar(64)	= NULL,
	@jdesc		univarchar(128)	= NULL,
	@jproperties	varchar(128)	= NULL,
	@jowner		varchar(30)	= NULL,
	@default_timeout int		= NULL,
	@tmpl_id	 int		= NULL
)
as
begin
	declare @sp_name varchar(32), @tjname univarchar(64), @tsjname univarchar(64), @wakeup_cmd varchar(16)
	declare @sjob_id int, @job_id int, @err int, @rows int, @msgno int, @is_admin int
	declare @new_sjproperties int, @new_jproperties int, @int_sjproperties int, @int_jproperties int
	declare @cur_sjname univarchar(64), @cur_sjdesc univarchar(128), @cur_sjowner varchar(32), @cur_enable int
	declare @cur_timeout int, @cur_sjproperties varchar(128), @cur_locale varchar(30), @cur_server varchar(30)
	declare @cur_jname univarchar(64), @cur_jdesc univarchar(128), @cur_jproperties varchar(128)
	declare @cur_jowner varchar(30), @cur_default_timeout int, @cur_tmpl_id int, @prev_jowner varchar(30)
	declare @vcname varchar(64)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_modifyscheduledjob'
	--
	select @is_admin=proc_role('js_admin_role')

	select @tsjname = ltrim(rtrim(@sjname_id))
	select @tjname = ltrim(rtrim(@jname_id))
	if @tsjname is not NULL
	begin
		exec @sjob_id=sp_js_check_id @name_id=@tsjname, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
		if @sjob_id < 0
		begin
			select @msgno = abs(@sjob_id)
			raiserror @msgno, @sp_name, '@sjname_id'
			return -@@error
		end
		--
		-- If there are some job arguments, get the @job_id value
		--
		if @jname is not NULL or @jdesc is not NULL or @jproperties is not NULL
			or @jowner is not NULL or @default_timeout is not NULL or @tmpl_id is not NULL
		begin
			select @job_id=sjob_job_id from sybmgmtdb..js_scheduledjobs where sjob_id=@sjob_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0 or @rows < 1
			begin
				-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
				raiserror 19050, @sp_name, '@sjname_id'
				return -@@error
			end
		end
		else
		begin
			select @job_id=NULL
		end
	end
	else if @tjname is not NULL
	begin
		exec @job_id=sp_js_check_id @name_id=@tjname, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
		if @job_id < 0
		begin
			select @msgno = abs(@job_id)
			raiserror @msgno, @sp_name, '@jname_id'
			return -@@error
		end
		select @sjob_id=NULL
	end
	else
	begin
		-- 19048 'Procedure %1!, parameter %2!, was not supplied, NULL or empty.'
		raiserror 19048, @sp_name, '@sjname_id or @jname_id'
		return -@@error
	end
	--
	-- Perform any validation that does not require locking
	--
	if @sjob_id is not NULL
	begin
		if @sjname is not NULL
		begin
			-- Validate the name
			select @tsjname = ltrim(rtrim(@sjname))
			exec @err=sp_js_check_id @name_id=@tsjname, @cmd=0, @table='sjob_', @return_id=1
			if @err < 0
			begin
				select @msgno = abs(@err)
				raiserror @msgno, @sp_name, '@sjname'
				return -@@error
			end
		end
		if @enable is not NULL
		begin
			if @enable != 0 and @enable != 1
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@enable', @enable
				return -@@error
			end
		end
		if @sjowner is not NULL
		begin
			if @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			--
			-- Validate server username
			--
			if suser_id(@sjowner) is NULL
			begin
				-- 19080 'Procedure %1!, %2! is not a valid server username.'
				raiserror 19080, @sp_name, @sjowner
				return -@@error
			end
		end
		if @timeout is not NULL
		begin
			if @timeout < 0
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@timeout', @timeout
				return -@@error
			end
		end
	end

	if @job_id is not NULL
	begin
		if @jname is not NULL
		begin
			-- Validate the name
			select @tjname = ltrim(rtrim(@jname))
			exec @err=sp_js_check_id @name_id=@tjname, @cmd=0, @table='job_', @return_id=1
			if @err < 0
			begin
				select @msgno = abs(@err)
				raiserror @msgno, @sp_name, '@jname'
				return -@@error
			end
		end
		if @jowner is not NULL
		begin
			if @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			--
			-- Validate server username
			--
			if suser_id(@jowner) is NULL
			begin
				-- 19080 'Procedure %1!, %2! is not a valid server username.'
				raiserror 19080, @sp_name, @jowner
				return -@@error
			end
		end
		if @tmpl_id is not NULL
		begin
			if @tmpl_id < 0
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@tmpl_id', @tmpl_id
				return -@@error
			end
		end
		if @default_timeout is not NULL
		begin
			if @default_timeout < 0
			begin
				-- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
				raiserror 19070, @sp_name, '@default_timeout', @default_timeout
				return -@@error
			end
		end
	end
	--
	-- begin tran
	-- update lock the job, then scheduled job
	-- read the current values
	-- perform any additional validation
	-- update the job, scheduled job - the order does 
	--	not matter once they have been locked.
	-- commit, release the locks
	-- tell ASE task
	--
	begin tran sp_modifyscheduledjob
	save tran nested_tran

	if @job_id is not NULL
	begin
		update sybmgmtdb..js_jobs set job_update=@@spid where job_id = @job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
		--
		-- if jowner has been supplied, we may need to disable all scheduled jobs
		-- that are not owned by that user.
		--
		if @jowner is not NULL
		begin
			update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid
				where sjob_job_id=@job_id and sjob_owner != @jowner
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
	end
	if @sjob_id is not NULL
	begin
		update sybmgmtdb..js_scheduledjobs set sjob_update=@@spid where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0 or @rows != 1
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
	end

	if @sjob_id is not NULL
	begin
		select @cur_sjname=sjob_name, @cur_sjowner=sjob_owner,
			@int_sjproperties=sjob_properties, @cur_sjproperties=sjob_uproperties,
			@cur_enable=sjob_enable, @cur_server=sjob_server,
			@cur_locale=sjob_locale, @cur_timeout=sjob_timeout_value
		from sybmgmtdb..js_scheduledjobs where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
		--
		-- process the scheduled jobs options
		--
		if @is_admin = 0 and @cur_sjowner != suser_name()
		begin
			rollback tran nested_tran
			commit tran
			-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
			raiserror 19084, @sp_name 
			return -@@error
		end
		-- only the owner may enable a sjob, js_admin_role may disable any sjob
		if @enable is not NULL
		begin
			if @cur_enable = 0 and @enable = 1 and @cur_sjowner != suser_name()
			begin
				rollback tran nested_tran
				commit tran
				-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
				raiserror 19084, @sp_name 
				return -@@error
			end
			select @cur_enable=@enable
		end
		-- Only a privileged user can check the roles granted to another user, so we 
		-- cannot see if the new owner has js_user_role or js_admin_role role. Therefore, we
		-- disable the scheduled job and the new job owner will have to re-enable it.
		if @sjowner is not NULL
		begin
			if @cur_sjowner != @sjowner select @cur_enable=0
			select @cur_sjowner=@sjowner
		end
		if @sjname is not NULL
		begin
			-- Check job name does not already exist - move to trigger
			if exists (select sjob_name from sybmgmtdb..js_scheduledjobs
					where sjob_name = @tsjname and sjob_owner = @cur_sjowner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19059 'Procedure %1!, a %2! already exists with the name %3!',
				select @vcname=@sjname
				raiserror 19059, @sp_name, 'scheduled job', @vcname
				return -@@error
			end
			select @cur_sjname=@tsjname
		end
		if @server  is not NULL	select @cur_server=nullif(@server, '')
		if @locale  is not NULL	select @cur_locale=nullif(@locale, '')
		if @timeout is not NULL	select @cur_timeout=@timeout
		if @sjproperties is not NULL
		begin
			--
			-- build the new properties
			--
			exec @err=sp_js_properties @int_sjproperties, 'sjob', @sjproperties, @new_sjproperties output, @cur_sjproperties output
			if @err < 0
			begin
				rollback tran nested_tran
				commit tran
				-- err -1 -> 19088 'Procedure %1!, @properties=''%2!'', invalid property name or value.'
				-- err -2 -> 19089 'Procedure %1!, @properties=''%2!'', a property cannot be used with the scheduledjob, job or schedule.
				if @err = -1
					raiserror 19088, @sp_name, @sjproperties
				else	raiserror 19089, @sp_name, @sjproperties
				return -@@error
			end
			--
			-- Currently none of the scheduledjobs properties requires any checks or action
			-- when they are set or cleared.
			select @int_sjproperties=@new_sjproperties
		end

--print 'name %1!, owner %2!, server %3!, props %4!, enable %5!, uprops %6!, locale %7!, timeout %8!', @cur_sjname,
--	@cur_sjowner, @cur_server, @int_sjproperties, @cur_enable, @cur_sjproperties, @cur_locale, @cur_timeout
		update sybmgmtdb..js_scheduledjobs set sjob_name=@cur_sjname, sjob_owner=@cur_sjowner,
			sjob_update=0, sjob_properties=@int_sjproperties,
			sjob_enable=@cur_enable, sjob_server=@cur_server,
			sjob_locale=@cur_locale, sjob_timeout_value=@cur_timeout,
			sjob_uproperties=@cur_sjproperties
	 	where sjob_id=@sjob_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_scheduledjobs', @err
			return -@@error
		end
	end

	if @job_id is not NULL
	begin
		select @cur_jname=job_name, @cur_jdesc=job_description, @cur_jowner=job_owner,
			@int_jproperties=job_properties, @cur_jproperties=job_uproperties,
			@cur_tmpl_id=job_tmpl_id, @cur_default_timeout=job_default_timeout
		from sybmgmtdb..js_jobs where job_id=@job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_jobs', @err
			return -@@error
		end
		--
		-- process the jobs options
		--
		if @is_admin = 0 and @cur_jowner != suser_name()
		begin
			rollback tran nested_tran
			commit tran
			-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
			raiserror 19084, @sp_name 
			return -@@error
		end
		select @prev_jowner=@cur_jowner		-- save the previous job_owner
		if @jowner is not NULL	select @cur_jowner=@jowner
		if @jname is not NULL
		begin
			-- Check job name does not already exist
			if exists (select job_name from sybmgmtdb..js_jobs
					where job_name = @tjname and job_owner = @cur_jowner)
			begin
				rollback tran nested_tran
				commit tran
				-- 19059 'Procedure %1!, a %2! already exists with the name %3!',
				select @vcname=@jname
				raiserror 19059, @sp_name, 'job', @vcname
				return -@@error
			end
			select @cur_jname=@tjname
		end
		if @jdesc is not NULL	select @cur_jdesc=@jdesc
		if @jproperties is not NULL
		begin
			--
			-- build the new properties
			--
			exec @err=sp_js_properties @int_jproperties, 'job', @jproperties, @new_jproperties output, @cur_jproperties output
			if @err < 0
			begin
				rollback tran nested_tran
				commit tran
				-- err -1 -> 19088 'Procedure %1!, @properties=''%2!'', invalid property name or value.'
				-- err -2 -> 19089 'Procedure %1!, @properties=''%2!'', a property cannot be used with the scheduledjob, job or schedule.
				if @err = -1
					raiserror 19088, @sp_name, @jproperties
				else	raiserror 19089, @sp_name, @jproperties
				return -@@error
			end
			--
			-- Currently none of the scheduledjobs properties requires any checks or action
			-- when they are set or cleared.
			--
			-- Check if run_as_owner has been turned on
			--
			if (@int_jproperties & 2 != 2) and (@new_jproperties & 2 = 2)
			begin
				if @cur_jowner != suser_name()
				begin
					rollback tran nested_tran
					commit tran
					-- 19087 'Procedure %1!, only the owner of a job may set the run_as_owner property.'
					raiserror 19087, @sp_name
					return -@@error
				end
			end
			--
			-- Check if shared flag is being cleared.
			--
			if (@int_jproperties & 32 = 32) and (@new_jproperties & 32 != 32)
			begin
				--	
				-- reject if currently used by other users
				--
				if exists (select sjob_job_id from sybmgmtdb..js_scheduledjobs
						where sjob_job_id=@job_id and sjob_owner != @cur_jowner)
				begin
					rollback tran nested_tran
					commit tran
					-- 19079 'Procedure %1!, unable to perform the operation while scheduled jobs are still using %2!.'
					select @vcname=@jname_id
					raiserror 19079, @sp_name, @vcname
					return -@@error
				end
			end
			select @int_jproperties=@new_jproperties
		end
		if @prev_jowner != @cur_jowner
		begin
			--
			-- Only a privileged user can check the roles granted to another user,
			-- so we cannot see if the new owner has js_user_role or js_admin_role role.
			-- Therefore we clear run_as_owner property when owner is changed.
			--
			exec @err=sp_js_properties @int_jproperties, 'job', 'run_as_owner=false', @new_jproperties output, @cur_jproperties output
			if @err = 0 select @int_jproperties=@new_jproperties
		end
		if @default_timeout is not NULL	select @cur_default_timeout=@default_timeout
		if @tmpl_id is not NULL	select @cur_tmpl_id=@tmpl_id


		update sybmgmtdb..js_jobs set job_name=@cur_jname, job_owner=@cur_jowner, job_description=@cur_jdesc,
			job_update=0, job_properties=@int_jproperties,
			job_default_timeout=@cur_default_timeout, job_tmpl_id=@cur_tmpl_id,
			job_uproperties=@cur_jproperties
	 	where job_id=@job_id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_jobs', @err
			return -@@error
		end
	end
	if @job_id is not NULL
	begin
		--
		-- disable all scheduled jobs using this job that are not owned by
		-- the new owner.
		--
		if @prev_jowner != @cur_jowner
		begin
			update sybmgmtdb..js_scheduledjobs set sjob_update=0, sjob_enable=0
				where sjob_job_id=@job_id and sjob_owner != @cur_jowner
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				rollback tran nested_tran
				commit tran
				-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
				raiserror 19074, @sp_name, 'js_scheduledjobs', @err
				return -@@error
			end
		end
	end

	commit tran
	--
	-- After the updates are done, inform the ASE task about:
	--	the enabling or disabling of a scheduled job
	--	the disabling of scheduled jobs due to job_owner change.
	-- 
	if @sjob_id is not NULL
	begin
		if @enable=0 and @cur_enable=1
			exec sp_js_wakeup 'job_disabled', @sjob_id
		else if @enable=1 and @cur_enable=0
			exec sp_js_wakeup 'job_enabled', @sjob_id
	end
	if @job_id is not NULL and @prev_jowner != @cur_jowner
	begin
		--
		-- disable all scheduled jobs using this job that are not owned by
		-- the new owner.
		--
		select @sjob_id=sjob_id from sybmgmtdb..js_scheduledjobs
			where sjob_job_id=@job_id and sjob_owner != @cur_jowner and sjob_enable=0
		select @rows=@@rowcount
		if @rows = 1
		begin
			exec sp_js_wakeup 'job_disabled', @sjob_id
		end
		else if @rows > 1
		begin
			declare new_jowner cursor for select sjob_id from sybmgmtdb..js_scheduledjobs
				where sjob_job_id=@job_id and sjob_owner != @cur_jowner and sjob_enable=0
				for read only
			open new_jowner
			fetch new_jowner into @sjob_id
			while @@sqlstatus = 0
			begin
				exec sp_js_wakeup 'job_disabled', @sjob_id
				fetch new_jowner into @sjob_id
			end
			close new_jowner
			deallocate cursor new_jowner
		end
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_modifyscheduledjob')
begin
	print 'Created sp_modifyscheduledjob'
	grant execute on sp_modifyscheduledjob to js_user_role
	grant execute on sp_modifyscheduledjob to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_modifyschedule')
    drop proc sp_modifyschedule
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_modifyschedule (
    @sname_id    univarchar(64),
    @sname       univarchar(64)   = NULL,
    @sdesc       univarchar(128)  = NULL,
    @sowner      varchar(30)      = NULL,
    @sproperties varchar(128)     = NULL,
    @reset       varchar(16)      = NULL,
    @repeats     int              = NULL,
    @units       varchar(8)       = NULL,
    @startdate   varchar(64)      = NULL,
    @starttime   varchar(64)      = NULL,
    @enddate     varchar(64)      = NULL,
    @endtime     varchar(64)      = NULL,
    @days        int              = NULL,
    @dates       int              = NULL,
    @udays       varchar(128)     = NULL,
    @udates      varchar(128)     = NULL
) as
begin
    declare @sp_name varchar(32)
          , @sched_id int
          , @err int
          , @rows int
          , @msgno int
          , @int_properties int
          , @tell_ase int
          , @is_admin int
          , @new_properties int
          , @sjob_id int
          , @sjob_count int
          , @tsname univarchar(64)
          , @int_repeats int
          , @int_days smallint
          , @int_dates int
          , @int_units char(1)
          , @cur_sname univarchar(64)
          , @cur_sdesc univarchar(128)
          , @cur_owner varchar(30)
          , @cur_uproperties varchar(128)
          , @cur_repeats int
          , @cur_units  varchar(8)
          , @cur_startdate datetime
          , @cur_starttime datetime
          , @cur_enddate datetime
          , @cur_endtime datetime
          , @cur_udays  varchar(128)
          , @cur_udates  varchar(128)
          , @cur_days smallint
          , @cur_dates int
          , @cur_urepeats varchar(32)
          , @new_sname univarchar(64)
          , @int_udays varchar(128)
          , @int_udates varchar(128)
          , @cur_expired int
          , @vcname varchar(64)

    if @@trancount = 0
        set chained off
    set transaction isolation level 1

    select @sp_name='sp_modifyschedule'
    select @is_admin=proc_role('js_admin_role')
    select @tell_ase=0

    --
    -- Validate and lookup the sname_id, as a name or as an id
    --
    select @tsname = rtrim(@sname_id)
    select @tsname = ltrim(@tsname)
    exec @sched_id=sp_js_check_id @name_id=@tsname, @cmd=2, @table='sched'
                                , @return_id=1, @is_admin=@is_admin
    if @sched_id < 0
    begin
        select @msgno = abs(@sched_id)
        raiserror @msgno, @sp_name, '@sname_id'
        return -@@error
    end

    --
    -- Validate the name for a schedule
    --
    if @sname is not NULL
    begin
        exec @err=sp_js_check_id @name_id=@sname, @cmd=0, @table='sched_'
        if @err < 0
        begin
            select @msgno = abs(@err), @vcname=@sname
            raiserror @msgno, @sp_name, @vcname
            return -@@error
        end
    end

    --
    -- Check the owner
    --
    -- mjm - what about the current owner, can't he change the ownership? NO!
    if @sowner is not NULL
    begin
        if @is_admin = 0
        begin
            -- 19077 'Procedure %1!, only a user with the js_admin_role role 
            -- can specify the owner.'
            raiserror 19077, @sp_name
            return -@@error
        end

        --
        -- Validate server username
        --
        if suser_id(@sowner) is NULL
        begin
            -- 19080 'Procedure %1!, %2! is not a valid server username.'
            raiserror 19080, @sp_name, @sowner
            return -@@error
        end

        --
        -- Only a privileged user can check the roles granted to another user,
        -- so we cannot see if the new owner has js_user_role or js_admin_role 
        -- role.  For a schedule this does not matter.
    end

    begin tran sp_modifyschedule
    save tran nested_tran

    --set the table lock column
    update sybmgmtdb..js_schedules 
       set sched_update=@@spid 
     where sched_id=@sched_id

    select @err=@@error, @rows=@@rowcount
    if @err != 0 or @rows != 1
    begin
        rollback tran nested_tran
        commit tran
        -- 19074 'Procedure %1!, failed to update an entry in the %2! table, 
        -- update error %3!.'
        raiserror 19074, @sp_name, 'js_schedules', @err
        return -@@error
    end

    -- select current schedule data before we change it
    select @cur_sname=sched_name, @cur_sdesc=sched_description
         , @cur_owner=sched_owner, @int_properties=sched_properties
         , @cur_repeats=sched_interval, @cur_units=sched_interval_units
         , @cur_startdate=sched_startdate, @cur_starttime=sched_starttime
         , @cur_enddate=sched_enddate, @cur_endtime=sched_endtime
         , @cur_expired=sched_expired, @cur_days=sched_days
         , @cur_dates=sched_dates, @cur_udays=sched_udays
         , @cur_udates=sched_udates, @cur_uproperties=sched_uproperties
     from sybmgmtdb..js_schedules 
    where sched_id = @sched_id

    select @err=@@error, @rows=@@rowcount
    if @err != 0 or @rows <= 0
    begin
        rollback tran nested_tran
        commit tran
        -- 19076 'Procedure %1!, failed to read an entry in the %2! table, 
        -- select error %3!.'
        raiserror 19076, @sp_name, 'js_schedules', @err
        return -@@error
    end
    --print 'name %1!, owner %2!, properties %3!, repeats %4!, units %5!
    --, days %6!, dates %7!, udays %8!, udates %9!',
    --@cur_sname, @cur_owner, @int_properties, @cur_repeats, @cur_units,
    --@cur_days, @cur_dates, @cur_udays, @cur_udates

    --  
    -- current user must be the schedule owner or be a js admin to change
    -- the schedule.
    -- 
    if @is_admin = 0 and @cur_owner != suser_name()
    begin
        rollback tran nested_tran
        commit tran
        -- 19084 'Procedure %1!, you do not have permission to modify the 
        -- specified scheduled job, job, schedule or running job.'
        raiserror 19084, @sp_name 
        return -@@error
    end

    if @sowner is not NULL    
        select @cur_owner=@sowner

    -- Validate properties if provided
    if @sproperties is not NULL
    begin
        --
        -- process property names
        --
        exec @err=sp_js_properties @int_properties, 'sched', @sproperties, 
                          @new_properties output, @cur_uproperties output
        if @err < 0
        begin
            rollback tran nested_tran
            commit tran
            -- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
            raiserror 19070, @sp_name, '@sproperties', @sproperties
            return -@@error
        end

        --
        -- reject un-share if currently used by other users
        --
        --print "sproperties is %1!", @sproperties
        if (@int_properties & 32 = 32) and (@new_properties & 32 != 32)
        begin
            if exists (select sjob_sched_id from sybmgmtdb..js_scheduledjobs
                where sjob_sched_id=@sched_id and sjob_owner != @cur_owner)
            begin
                rollback tran nested_tran
                commit tran
                -- 19079 'Procedure %1!, unable to perform the operation while 
                -- scheduled jobs are still using %2!.'
                select @vcname=@cur_sname
                raiserror 19079, @sp_name, @vcname
                return -@@error
            end
        end
        select @int_properties=@new_properties
    end

    if @sname is not NULL    
        select @new_sname=@sname

    if @sdesc is not NULL    
        select @cur_sdesc=@sdesc

    --this flag indicates that we need to clear repeating values before updating
    -- clear fields if reset flag was set
    -- mjm : not being used by GUI at this time.
    if @reset = 'true'
    begin
        select @cur_repeats=0
             , @cur_units=' '
             , @cur_startdate=getdate()
             , @cur_starttime=NULL
             , @cur_enddate=NULL
             , @cur_endtime=NULL
             , @cur_days=0
             , @cur_dates=0
             , @cur_udays=NULL
             , @cur_udates=NULL
             , @tell_ase=1
    end

    if @repeats is NULL
        select @repeats = @cur_repeats
    else 
        select @cur_repeats=@repeats, @tell_ase=1
    if @units is not NULL
            select @cur_units=@units, @tell_ase=1

    set arithabort off    -- restored on return

    if @startdate is not NULL
    begin
        if @startdate = '' select @startdate=NULL
        select @cur_startdate=convert(datetime, @startdate)
        if @@error != 0
        begin
            -- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
            raiserror 19070, @sp_name, '@startdate', @startdate
            return -@@error
        end
        select @tell_ase=1
    end

    if @starttime is not NULL
    begin
        if @starttime = '' 
            select @starttime=NULL
        select @cur_starttime=convert(datetime, @starttime)
        if @@error != 0
        begin
            -- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
            raiserror 19070, @sp_name, '@starttime', @starttime
            return -@@error
        end
        select @tell_ase=1
    end
    if @enddate is not NULL
    begin
        if @enddate = '' 
            select @enddate=NULL
        select @cur_enddate=convert(datetime, @enddate)
        if @@error != 0
        begin
            -- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
            raiserror 19070, @sp_name, '@enddate', @enddate
            return -@@error
        end
        select @tell_ase=1
    end
    if @endtime is not NULL
    begin
        if @endtime = '' 
            select @endtime=NULL
        select @cur_endtime=convert(datetime, @endtime)
        if @@error != 0
        begin
            -- 19070 'Procedure %1!, cannot set option (%2!) to value (%3!).'
            raiserror 19070, @sp_name, '@endtime', @endtime
            return -@@error
        end
        select @tell_ase=1
    end

    set arithabort on

    -- Checking days and dates now--tread lightly here
    -- We've got to set a priority, here it is:
    --   days
    --   udays
    --   dates
    --   udates
    --
    if @days is not NULL and @days <> @cur_days
    begin
        --print 'days not NULL and changed'
        select @cur_days=@days
             , @tell_ase=1
             , @cur_udays=NULL
    end
    else if @udays is not NULL and @udays <> @cur_udays
    begin
        --print 'udays not NULL and changed'
        select @cur_udays=@udays
             , @tell_ase=1
             , @cur_days=NULL
    end

    if @dates is not NULL and @dates <> @cur_dates
    begin
        --print 'dates not NULL and changed'
        select @cur_dates=@dates
             , @tell_ase=1
             , @cur_udates=NULL
    end
    else if @udates is not NULL and @udates <> @cur_udates
    begin
        --print 'udates not NULL and changed'
        select @cur_udates=@udates
             , @tell_ase=1
             , @cur_dates=NULL
    end

    --print 'days %1!, dates %2!, udays %3!, udates %4!',
    --      @cur_days, @cur_dates, @cur_udays, @cur_udates
    --print 'name %1!, owner %2!, properties %3!, repeats %4!, units %5!
    -- , days %6!, dates %7!, udays %8!, udates %9!',
    -- @new_sname, @cur_owner, @int_properties, @cur_repeats, @cur_units,
    -- @cur_days, @cur_dates, @cur_udays, @cur_udates

    exec @err=sp_js_checksched @caller=@sp_name, @sname=@new_sname, 
            @sdesc=@cur_sdesc,
            @sowner=@cur_owner, @sched_id=@sched_id,
            @repeats=@cur_repeats, @units=@cur_units,
            @startdate=@cur_startdate, @starttime=@cur_starttime,
            @enddate=@cur_enddate, @endtime=@cur_endtime,
            @days=@cur_days, @dates=@cur_dates,
            @udays=@cur_udays, @udates=@cur_udates,
            @int_repeats=@int_repeats output, @int_units=@int_units output,
            @int_days=@int_days output, @int_dates=@int_dates output,
            @int_udays=@int_udays output, @int_udates=@int_udates output

    if @err < 0
    begin
        rollback tran nested_tran
        commit tran
        -- sp_js_checksched raises the error
        return @err
    end

    --print 'name %1!, owner %2!, properties %3!, repeats %4!, units %5!, 
    --days %6!, dates %7!, udays %8!, udates %9!',
    --@new_sname, @cur_owner, @int_properties, @cur_repeats, @cur_units,
    --@int_days, @int_dates, @int_udays, @int_udates

    -- Now that we've verified we have valid schedule values, we need to update
    -- some variables that will be used in the schedule update statement
    if @new_sname is not NULL    
        select @cur_sname=@new_sname

    if (@cur_expired & 1) = 1    
        select @cur_expired=@cur_expired - 1

    update sybmgmtdb..js_schedules 
       set sched_name=@cur_sname, sched_description=@cur_sdesc
         , sched_properties=@int_properties, sched_owner=@cur_owner
         , sched_interval=@int_repeats, sched_interval_units=@int_units
         , sched_update=0
         , sched_uinterval=convert(varchar(32), @int_repeats) + @cur_units
         , sched_startdate=@cur_startdate, sched_starttime=@cur_starttime
         , sched_enddate=@cur_enddate, sched_endtime=@cur_endtime
         , sched_days=@int_days, sched_udays=@int_udays
         , sched_dates=@int_dates, sched_udates=@int_udates
         , sched_uproperties=@cur_uproperties, sched_expired=@cur_expired
     where sched_id=@sched_id

    select @err=@@error
    if @err != 0
    begin
        rollback tran nested_tran
        commit tran
        -- 19074 'Procedure %1!, failed to update an entry in the %2! table,
        -- update error %3!.'
        raiserror 19074, @sp_name, 'js_schedules', @err
        return -@@error
    end
    commit tran

    if @tell_ase != 0
    begin
        select @sjob_id=sjob_id 
          from sybmgmtdb..js_scheduledjobs 
         where sjob_sched_id=@sched_id and sjob_enable=1

        select @tell_ase=@@rowcount
        if @tell_ase = 1
        begin
            exec sp_js_wakeup 'new_schedule', @sjob_id
            return 0
        end

        declare new_sched cursor for select sjob_id 
                from sybmgmtdb..js_scheduledjobs
               where sjob_sched_id=@sched_id and sjob_enable=1
                 for read only
        open new_sched
        fetch new_sched into @sjob_id
        while @@sqlstatus = 0
        begin
            exec sp_js_wakeup 'new_schedule', @sjob_id
            fetch new_sched into @sjob_id
        end
        close new_sched
        deallocate cursor new_sched
    end
    return 0
end
go
if exists (select name from sysobjects where name = 'sp_modifyschedule')
begin
    print 'Created sp_modifyschedule'
    grant execute on sp_modifyschedule to js_user_role
    grant execute on sp_modifyschedule to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_dropscheduledjob')
	drop proc sp_dropscheduledjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_dropscheduledjob (
	@sjname_id	univarchar(64),
	@option		univarchar(512)	= NULL
)
as
begin
	declare @err int, @name_id univarchar(128)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	if @option = 'combined'
		select @option='sp_name=sp_dropscheduledjob,all', @name_id='sjname=' + @sjname_id
	else if @option is not NULL
		select @option='sp_name=sp_dropscheduledjob,' + @option, @name_id='sjname=' + @sjname_id
	else
		select @option='sp_name=sp_dropscheduledjob', @name_id='sjname=' + @sjname_id
	exec @err=sp_sjobdrop @name=@name_id, @option=@option
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_dropscheduledjob')
begin
	print 'Created sp_dropscheduledjob'
	grant execute on sp_dropscheduledjob to js_user_role
	grant execute on sp_dropscheduledjob to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_dropjob')
	drop proc sp_dropjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_dropjob (
	@jname_id	univarchar(64),
	@option         univarchar(512) = NULL
)
as
begin
	declare @err int, @name_id univarchar(128)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select @option='sp_name=sp_dropjob,' + @option, @name_id='jname=' + @jname_id
	exec @err=sp_sjobdrop @name=@name_id, @option=@option
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_dropjob')
begin
	print 'Created sp_dropjob'
	grant execute on sp_dropjob to js_user_role
	grant execute on sp_dropjob to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_dropschedule')
	drop proc sp_dropschedule
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_dropschedule (
	@sname_id	univarchar(64),
	@option         univarchar(512) = NULL
)
as
begin
	declare @err int, @name_id univarchar(128)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select @option='sp_name=sp_dropschedule,' + @option, @name_id='sname=' + @sname_id
	exec @err=sp_sjobdrop @name=@name_id, @option=@option
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_dropschedule')
begin
	print 'Created sp_dropschedule'
	grant execute on sp_dropschedule to js_user_role
	grant execute on sp_dropschedule to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_copyjob')
	drop proc sp_copyjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_copyjob (
	@jname_id		univarchar(64),
	@newname		univarchar(64)
)
as
begin
	declare @err int, @name univarchar(80), @name2 univarchar(128)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1

	select @name='jname=' + @jname_id, @name2='sp_name=sp_copyjob,newname=' + @newname
	exec @err=sp_sjobcopy @name=@name, @option=@name2
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_copyjob')
begin
	print 'Created sp_copyjob'
	grant execute on sp_copyjob to js_user_role
	grant execute on sp_copyjob to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_copyschedule')
	drop proc sp_copyschedule
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_copyschedule (
	@sname_id		univarchar(64),
	@newsname		univarchar(64)
)
as
begin
	declare @err int, @name univarchar(80), @name2 univarchar(129)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1

	select @name='sname=' + @sname_id, @name2='sp_name=sp_copyschedule,newname=' + @newsname
	exec @err=sp_sjobcopy @name=@name, @option=@name2
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_copyschedule')
begin
	print 'Created sp_copyschedule'
	grant execute on sp_copyschedule to js_user_role
	grant execute on sp_copyschedule to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_listscheduledjob')
	drop proc sp_listscheduledjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_listscheduledjob (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(128), @opt_name univarchar(32), @opt_value univarchar(96)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(64)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int
	declare @err int, @rows int, @msgno int, @is_admin int, @sjob_id int, @job_id int, @run_id int
	declare @list_arg int, @sjob_arg int, @job_arg int, @owner_arg int, @user_arg int, @runid_arg int, @all_arg int
	declare @list_val varchar(32), @name_val univarchar(64), @owner_val varchar(32), @user_val varchar(32)
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_listscheduledjob'
	select	@list_arg =0, @sjob_arg =0, @job_arg =0, @owner_arg =0, @user_arg =0, @runid_arg =0, @all_arg =0

	select @is_admin=proc_role('js_admin_role')
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @value=ltrim(rtrim(@option))
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0					-- @option=opt_name
		begin
			select @opt_val_pair=ltrim(rtrim(@opt_val_pair))
			if @opt_val_pair = 'all' or @opt_val_pair = 'all_users'
			begin
				select @all_arg=1, @opt_name=@opt_val_pair
			end
			else
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_val_pair
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @eq_pos = @opt_val_len			-- @property=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end

		if @opt_name = 'list'
		begin
			if @opt_value != 'scheduled' and @opt_value != 'unscheduled' and @opt_value != 'running'
				and @opt_value != 'scheduled_short' and @opt_value != 'unscheduled_short'
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_name
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			select @list_arg=1, @list_val=@opt_value
		end
		else if @opt_name = 'all' or @opt_name = 'all_users'
		begin
			if @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
		end
		else if @opt_name = 'sjname'
		begin
			exec @sjob_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sjob', @return_id=1, @is_admin=@is_admin
			if @sjob_id < 0
			begin
				select @msgno = abs(@sjob_id), @vcbuf1=@opt_val_pair
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @sjob_arg=1
		end
		else if @opt_name = 'jname'
		begin
			exec @job_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
			if @job_id < 0
			begin
				select @msgno = abs(@job_id), @vcbuf1=@opt_val_pair
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @name_val=job_name from sybmgmtdb..js_jobs where job_id=@job_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0 or @rows <= 0
				return @err
			select @job_arg=1
		end
		else if @opt_name = 'owner'
		begin
			if @opt_value != suser_name() and @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			select @owner_arg=1, @owner_val=@opt_value
		end
		else if @opt_name = 'user'
		begin
			if @opt_value != suser_name() and @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			select @user_arg=1, @user_val=@opt_value
		end
		else if @opt_name = 'runid'
		begin
			exec @run_id=sp_js_check_id @name_id=@opt_value, @cmd=1, @table='jsh', @is_admin=@is_admin
			if @run_id < 0
			begin
				select @msgno = abs(@run_id), @vcbuf1=@opt_val_pair
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @runid_arg=1
		end
		else
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		
		select @curpos=@end_pos + 1
	end

	if @list_val = 'running'
	begin
		if @all_arg != 1 and @user_arg = 0 and @owner_arg = 0
			select @user_val = suser_name(), @user_arg=1
		select  sjob_runid=jsh_exid,		sjob_id=jsh_sjobid,
			job_name=jsh_jobname,		job_sched_name=jsh_schedname,
			job_state=jsh_state,		job_start=jsh_jobstart, 
			job_user_run=jsh_user_run,	job_user_req=jsh_user_req,
			job_short_message=jsh_smsg,	job_long_message=jsh_lmsg
		from sybmgmtdb..js_history where
			(@runid_arg  = 0  or  jsh_exid     = @run_id )     and
			(jsh_state like '[QR]%' or jsh_state like '[CTX]1') and
			(@sjob_arg   = 0  or  jsh_sjobid   = @sjob_id)     and
			(@job_arg    = 0  or  jsh_jobname  = @name_val)    and
			(@owner_arg  = 0  or  jsh_user_run = @owner_val)   and
			(@user_arg   = 0  or  jsh_user_req = @user_val)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @all_arg = 0 and @owner_arg = 0
		select @owner_val = suser_name()
	if @list_val = 'scheduled_short'
	begin
		-- TODO what happens about sjob exec by different users in the history select ?
		select	sjob_id=sjob_id, sjob_job_id=sjob_job_id,
			sjob_sched_id=sjob_sched_id, sjob_enable=sjob_enable,
			sjob_properties=sjob_uproperties, sjob_owner=sjob_owner,
			sjob_created=sjob_created, sjob_server=sjob_server,
			sjob_timeout_value=sjob_timeout_value, sjob_locale=sjob_locale,

			job_default_timeout=job_default_timeout,
			job_name=job_name,

			sched_name=sched_name,	sjob_next_start=jsc_start,
			sjob_last_start=jsh_jobstart, sjob_state=jsh_state,
			sjob_last_exit_code=jsh_exit_code, sjob_last_atat_error=jsh_atat_error
		from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules, sybmgmtdb..js_callouts, sybmgmtdb..js_history where
			(js_scheduledjobs.sjob_job_id   = js_jobs.job_id)         and
			(js_scheduledjobs.sjob_sched_id = js_schedules.sched_id)  and
			(js_scheduledjobs.sjob_id      *= js_callouts.jsc_sjobid) and
			(js_scheduledjobs.sjob_id       = js_history.jsh_sjobid
			    and js_history.jsh_exid =
				(select max(jsh_exid) from sybmgmtdb..js_history jsh1 -- get one jsh_exid
				 where jsh1.jsh_sjobid = js_scheduledjobs.sjob_id
					and jsh1.jsh_jobstart =		   -- get the last starttime
					(select max(jsh_jobstart) from sybmgmtdb..js_history jsh2
					 where jsh2.jsh_sjobid = js_scheduledjobs.sjob_id
					)
				)
			) and
			(@sjob_arg  = 0 or sjob_id     = @sjob_id)                and
			(@job_arg   = 0 or sjob_job_id = @job_id)                 and
			( @all_arg = 1
			   or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)) )
			   or (@owner_arg = 1 and sjob_owner = @owner_val)
			)
		union all
		select	sjob_id=sjob_id, sjob_job_id=sjob_job_id,
			sjob_sched_id=sjob_sched_id, sjob_enable=sjob_enable,
			sjob_properties=sjob_uproperties, sjob_owner=sjob_owner,
			sjob_created=sjob_created, sjob_server=sjob_server,
			sjob_timeout_value=sjob_timeout_value, sjob_locale=sjob_locale,

			job_default_timeout=job_default_timeout,
			job_name=job_name,

			sched_name=sched_name,	sjob_next_start=jsc_start,
			sjob_last_start=NULL, sjob_state=jsc_state,
			sjob_last_exit_code=NULL,	sjob_last_atat_error=NULL
		from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules, sybmgmtdb..js_callouts where
			(js_scheduledjobs.sjob_job_id   = js_jobs.job_id)         and
			(js_scheduledjobs.sjob_sched_id = js_schedules.sched_id)  and
			(js_scheduledjobs.sjob_id      *= js_callouts.jsc_sjobid) and
			(not exists (select jsh_sjobid from sybmgmtdb..js_history where
					jsh_sjobid = js_scheduledjobs.sjob_id))   and
			(@sjob_arg  = 0 or sjob_id     = @sjob_id)                and
			(@job_arg   = 0 or sjob_job_id = @job_id)                 and
			( @all_arg = 1
			   or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)) )
			   or (@owner_arg = 1 and sjob_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @list_val = 'scheduled'
	begin
		select	sjob_id=sjob_id, sjob_job_id=sjob_job_id,
			sjob_sched_id=sjob_sched_id, sjob_enable=sjob_enable,
			sjob_properties=sjob_uproperties, sjob_owner=sjob_owner,
			sjob_created=sjob_created, sjob_server=sjob_server,
			sjob_timeout_value=sjob_timeout_value, sjob_locale=sjob_locale,

			job_type=job_type,	job_properties=job_uproperties,
			job_owner=job_owner,	job_created=job_created,
			job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id,
			job_name=job_name,	job_description=job_description,

			sched_name=sched_name,	sjob_next_start=jsc_start,
			sjob_last_start=jsh_jobstart, sjob_state=jsh_state,
			sjob_last_exit_code=jsh_exit_code, sjob_last_atat_error=jsh_atat_error
		from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules, sybmgmtdb..js_callouts, sybmgmtdb..js_history where
			(js_scheduledjobs.sjob_job_id   = js_jobs.job_id)         and
			(js_scheduledjobs.sjob_sched_id = js_schedules.sched_id)  and
			(js_scheduledjobs.sjob_id      *= js_callouts.jsc_sjobid) and
			(js_scheduledjobs.sjob_id       = js_history.jsh_sjobid
			    and js_history.jsh_exid =
				(select max(jsh_exid) from sybmgmtdb..js_history jsh1 -- get one jsh_exid
				 where jsh1.jsh_sjobid = js_scheduledjobs.sjob_id
					and jsh1.jsh_jobstart =		   -- get the last starttime
					(select max(jsh_jobstart) from sybmgmtdb..js_history jsh2
					 where jsh2.jsh_sjobid = js_scheduledjobs.sjob_id
					)
				)
			) and
			(@sjob_arg  = 0 or sjob_id     = @sjob_id)                and
			(@job_arg   = 0 or sjob_job_id = @job_id)                 and
			( @all_arg = 1
			   or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)) )
			   or (@owner_arg = 1 and sjob_owner = @owner_val)
			)
		union all
		select	sjob_id=sjob_id, sjob_job_id=sjob_job_id,
			sjob_sched_id=sjob_sched_id, sjob_enable=sjob_enable,
			sjob_properties=sjob_uproperties, sjob_owner=sjob_owner,
			sjob_created=sjob_created, sjob_server=sjob_server,
			sjob_timeout_value=sjob_timeout_value, sjob_locale=sjob_locale,

			job_type=job_type,	job_properties=job_uproperties,
			job_owner=job_owner,	job_created=job_created,
			job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id,
			job_name=job_name,	job_description=job_description,

			sched_name=sched_name,	sjob_next_start=jsc_start,
			sjob_last_start=NULL, sjob_state=jsc_state,
			sjob_last_exit_code=NULL,	sjob_last_atat_error=NULL
		from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs, sybmgmtdb..js_schedules, sybmgmtdb..js_callouts where
			(js_scheduledjobs.sjob_job_id   = js_jobs.job_id)         and
			(js_scheduledjobs.sjob_sched_id = js_schedules.sched_id)  and
			(js_scheduledjobs.sjob_id      *= js_callouts.jsc_sjobid) and
			(not exists (select jsh_sjobid from sybmgmtdb..js_history where
					jsh_sjobid = js_scheduledjobs.sjob_id))   and
			(@sjob_arg  = 0 or sjob_id     = @sjob_id)                and
			(@job_arg   = 0 or sjob_job_id = @job_id)                 and
			( @all_arg = 1
			   or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)) )
			   or (@owner_arg = 1 and sjob_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @list_val = 'unscheduled_short'
	begin
		select  job_id=job_id,		job_name=job_name,
			job_description=job_description,
			job_owner=job_owner,	job_created=job_created
		from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_arg   = 0 or job_id    = @job_id)                and
			( @all_arg = 1
			   or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)) )
			   or (@owner_arg = 1 and job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @list_val = 'unscheduled'
	begin
		select  job_id=job_id,		job_name=job_name,
			job_description=job_description,
			job_owner=job_owner,	job_created=job_created,
			job_type=job_type,	job_properties=job_uproperties,
			job_default_timeout=job_default_timeout,
			job_tmpl_id=job_tmpl_id
		from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_arg   = 0 or job_id    = @job_id)                and
			( @all_arg = 1
			   or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)) )
			   or (@owner_arg = 1 and job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @list_val is NULL
	begin
		select	sjob_id=sjob_id, sjob_job_id=sjob_job_id, sjob_sched_id=sjob_sched_id,
			sjob_owner=sjob_owner,		sjob_created=sjob_created,
			sjob_server=sjob_server,	sjob_enable=sjob_enable,
			sjob_timeout_value=sjob_timeout_value, sjob_properties=sjob_uproperties,
			sjob_locale=sjob_locale,

			job_name=job_name,	job_description=job_description,
			job_owner=job_owner,	job_created=job_created,
			job_type=job_type,	job_properties=job_uproperties,
			job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id
		from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs where
			(js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_arg   = 0 or sjob_job_id = @job_id)       and
			(@owner_arg = 0 or sjob_owner  = @owner_val)
		union all
		select	sjob_id=NULL, sjob_job_id=job_id, sjob_sched_id=NULL,
			sjob_owner=NULL,	sjob_created=NULL,
			sjob_server=NULL,	sjob_enable=NULL,
			sjob_timeout_value=NULL,	sjob_properties=NULL,
			sjob_locale=NULL,

			job_name=job_name,	job_description=job_description,
			job_owner=job_owner,	job_created=job_created,
			job_type=job_type,	job_properties=job_uproperties,
			job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id
		from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_arg   = 0 or job_id    = @job_id)  and
			(@owner_arg = 0 or job_owner = @owner_val)
		select @err=@@error, @rows=@@rowcount
	end
	else
	begin
		select	sjob_id=sjob_id, sjob_job_id=sjob_job_id, sjob_sched_id=sjob_sched_id,
			sjob_owner=sjob_owner,		sjob_created=sjob_created,
			sjob_server=sjob_server,	sjob_enable=sjob_enable,
			sjob_timeout_value=sjob_timeout_value, sjob_properties=sjob_uproperties,
			sjob_locale=sjob_locale,

			job_name=job_name,	job_description=job_description,
			job_owner=job_owner,	job_created=job_created,
			job_type=job_type,	job_properties=job_uproperties,
			job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id
		from sybmgmtdb..js_scheduledjobs, sybmgmtdb..js_jobs where
			(js_scheduledjobs.sjob_job_id = js_jobs.job_id)    and
			(@job_arg  = 0 or sjob_job_id = @job_id)           and
			( @all_arg = 1
			   or (@owner_arg = 0 and (sjob_owner = @owner_val or (sjob_properties & 64 = 64)) )
			   or (@owner_arg = 1 and sjob_owner = @owner_val)
			)
		union all
		select	sjob_id=NULL, sjob_job_id=job_id, sjob_sched_id=NULL,
			sjob_owner=NULL,	sjob_created=NULL,
			sjob_server=NULL,	sjob_enable=NULL,
			sjob_timeout_value=NULL,	sjob_properties=NULL,
			sjob_locale=NULL,

			job_name=job_name,	job_description=job_description,
			job_owner=job_owner,	job_created=job_created,
			job_type=job_type,	job_properties=job_uproperties,
			job_default_timeout=job_default_timeout,	job_tmpl_id=job_tmpl_id
		from sybmgmtdb..js_jobs where
			not exists (select sjob_id from sybmgmtdb..js_scheduledjobs where
				js_scheduledjobs.sjob_job_id = js_jobs.job_id) and
			(@job_arg  = 0 or job_id = @job_id)                    and
			( @all_arg = 1
			   or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)) )
			   or (@owner_arg = 1 and job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_listscheduledjob')
begin
	print 'Created sp_listscheduledjob'
	grant execute on sp_listscheduledjob to public
end
go
go
if exists (select name from sysobjects where name = 'sp_listjob')
	drop proc sp_listjob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_listjob (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(128), @opt_name univarchar(32), @opt_value univarchar(96)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(64)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @err int, @rows int, @msgno int, @is_admin int, @job_id int, @properties int
	declare @list_arg int, @job_arg int, @owner_arg int, @all_arg int
	declare @list_val varchar(32), @owner_val varchar(32)
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_listjob'
	select	@list_arg =0, @job_arg =0, @owner_arg =0, @all_arg =0

	select @is_admin=proc_role('js_admin_role')
	--
	-- If there is no argument, show all jobs visible to the caller
	--
	select @value=ltrim(rtrim(@option))
	if @value is NULL
	begin
		select  job_id=job_id,		job_name=job_name,
			job_description=job_description,
			job_owner=job_owner,	job_created=job_created,
			job_type=job_type,	job_properties=job_uproperties,
			job_default_timeout=job_default_timeout,
			job_tmpl_id=job_tmpl_id
		from sybmgmtdb..js_jobs where job_owner = suser_name() or (job_properties & 32 = 32)
		return @@error
	end
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0					-- @option=opt_name
		begin
			select @opt_val_pair=ltrim(rtrim(@opt_val_pair))
			if @opt_val_pair = 'all' or @opt_val_pair = 'all_users'
			begin
				select @all_arg=1, @opt_name=@opt_val_pair
			end
			else
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_val_pair
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @eq_pos = @opt_val_len			-- @property=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))
	
			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		--
		-- Process the opt_name=opt_value pairs
		--
		if @opt_name = 'list'
		begin
			if @opt_value != 'short' and @opt_value != 'full' and @opt_value != 'ids'
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_name
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			select @list_arg=1, @list_val=@opt_value
		end
		else if @opt_name = 'all' or @opt_name = 'all_users'
		begin
			if @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			select @all_arg=1
		end
		else if @opt_name = 'jname'
		begin
			exec @job_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
			if @job_id < 0
			begin
				select @msgno = abs(@job_id), @vcbuf1=@opt_val_pair
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @job_arg=1
		end
		else if @opt_name = 'owner'
		begin
			if @opt_value != suser_name() and @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			select @owner_arg=1, @owner_val=@opt_value
		end
		else
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		select @curpos=@end_pos + 1
	end
	if @job_arg = 1
	begin
		if @is_admin = 0
		begin
			select @opt_value=job_owner,@properties=job_properties
				from sybmgmtdb..js_jobs where job_id=@job_id
			-- TODO job has gone away - not an error, look for other cases
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_jobs', @err
				return -@@error
			end
			if @rows < 1
			begin
				-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
				select @vcbuf1=@option
				raiserror 19050, @sp_name, @vcbuf1
				return -@@error
			end
			if @opt_value != suser_name() and (@properties & 32 != 32)
			begin
				-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
				raiserror 19083, @sp_name, @job_id
				return -@@error
			end
		end
	end
	if @all_arg = 0 and @owner_arg = 0	select @owner_val = suser_name()
	if @list_val = 'ids'
	begin
		--
		-- don't include shared when the owner was given
		select	job_id=job_id from sybmgmtdb..js_jobs where
			(@job_arg   = 0 or job_id = @job_id) and
			( @all_arg = 1
			   or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)) )
			   or (@owner_arg = 1 and job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @list_val = 'short'
	begin
		select	job_id=job_id,		job_name=job_name,
			job_description=job_description,
			job_owner=job_owner,	job_created=job_created
		from sybmgmtdb..js_jobs where
			(@job_arg   = 0 or job_id = @job_id) and
			( @all_arg = 1
			   or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)) )
			   or (@owner_arg = 1 and job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @list_val is NULL or @list_val = 'full'
	begin
		select  job_id=job_id,		job_name=job_name,
			job_description=job_description,
			job_owner=job_owner,	job_created=job_created,
			job_type=job_type,	job_properties=job_uproperties,
			job_default_timeout=job_default_timeout,
			job_tmpl_id=job_tmpl_id
		from sybmgmtdb..js_jobs where
			(@job_arg   = 0 or job_id = @job_id) and
			( @all_arg = 1
			   or (@owner_arg = 0 and (job_owner = @owner_val or (job_properties & 32 = 32)) )
			   or (@owner_arg = 1 and job_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_listjob')
begin
	print 'Created sp_listjob'
	grant execute on sp_listjob to public
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_listschedule')
	drop proc sp_listschedule
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_listschedule (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @value univarchar(512), @opt_val_pair univarchar(128), @opt_name univarchar(32), @opt_value univarchar(96)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(64)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @err int, @rows int, @msgno int, @is_admin int, @sched_id int, @properties int
	declare @list_arg int, @sched_arg int, @owner_arg int, @all_arg int
	declare @list_val varchar(32), @owner_val varchar(32)
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_listschedule'
	select	@list_arg =0, @sched_arg =0, @owner_arg =0, @all_arg =0

	select @is_admin=proc_role('js_admin_role')
	--
	-- If there is no argument, show all schedules visible to the caller
	--
	select @value=ltrim(rtrim(@option))
	if @value is NULL
	begin
		select	sched_id=sched_id, sched_name=sched_name,
			sched_description=sched_description,
			sched_owner=sched_owner,	sched_created=sched_created, 
			sched_type=sched_type,		sched_properties=sched_uproperties,
			sched_interval=sched_interval,	sched_interval_units=sched_interval_units,
			sched_startdate=sched_startdate, sched_starttime=sched_starttime,
			sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
			sched_days=sched_days,		sched_dates=sched_dates
		from sybmgmtdb..js_schedules where sched_owner = suser_name() or (sched_properties & 32 = 32)
		return @@error
	end
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0					-- @option=opt_name
		begin
			select @opt_val_pair=ltrim(rtrim(@opt_val_pair))
			if @opt_val_pair = 'all' or @opt_val_pair = 'all_users'
			begin
				select @all_arg=1, @opt_name=@opt_val_pair
			end
			else
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_val_pair
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
		end
		else if @eq_pos = @opt_val_len			-- @property=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end

		if @opt_name = 'list'
		begin
			if @opt_value != 'short' and @opt_value != 'full'
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                		select @vcbuf1=@option, @vcbuf2=@opt_name
				raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
				return -@@error
			end
			select @list_arg=1, @list_val=@opt_value
		end
		else if @opt_name = 'all' or @opt_name = 'all_users'
		begin
			if @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
		end
		else if @opt_name = 'sname'
		begin
			exec @sched_id=sp_js_check_id @name_id=@opt_value, @cmd=2, @table='sched', @return_id=1, @is_admin=@is_admin
			if @sched_id < 0
			begin
				select @msgno = abs(@sched_id), @vcbuf1=@opt_val_pair
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
			select @sched_arg=1
		end
		else if @opt_name = 'owner'
		begin
			if @opt_value != suser_name() and @is_admin = 0
			begin
				-- 19077 'Procedure %1!, only a user with the js_admin_role role can specify the owner.'
				raiserror 19077, @sp_name
				return -@@error
			end
			select @owner_arg=1, @owner_val=@opt_value
		end
		else
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		select @curpos=@end_pos + 1
	end
	if @sched_arg = 1
	begin
		if @is_admin = 0
		begin
			select @opt_value=sched_owner,@properties=sched_properties
				from sybmgmtdb..js_schedules where sched_id=@sched_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
			begin
				-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
				raiserror 19076, @sp_name, 'js_schedules', @err
				return -@@error
			end
			if @rows < 1
			begin
				-- 19051 'Procedure %1!, parameter %2!, the specified schedule does not exist.'
				select @vcbuf1=@option
				raiserror 19051, @sp_name, @vcbuf1
				return -@@error
			end
			if @opt_value != suser_name() and (@properties & 32 != 32)
			begin
				-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
				raiserror 19083, @sp_name, @sched_id
				return -@@error
			end
		end
	end
	if @all_arg = 0 and @owner_arg = 0	select @owner_val = suser_name()
	if @list_val = 'short'
	begin
		select	sched_id=sched_id,		sched_name=sched_name,
			sched_description=sched_description,
			sched_owner=sched_owner,	sched_created=sched_created
		from sybmgmtdb..js_schedules where
			(@sched_arg   = 0 or sched_id = @sched_id) and
			( @all_arg = 1
			   or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)) )
			   or (@owner_arg = 1 and sched_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	if @list_val is NULL or @list_val = 'full'
	begin
		select	sched_id=sched_id,	sched_name=sched_name,
			sched_description=sched_description,
			sched_owner=sched_owner,	sched_created=sched_created, 
			sched_type=sched_type,		sched_properties=sched_uproperties,
			sched_interval=sched_interval,	sched_interval_units=sched_interval_units,
			sched_startdate=sched_startdate, sched_starttime=sched_starttime,
			sched_enddate=sched_enddate,	sched_endtime=sched_endtime,
			sched_days=sched_days,		sched_dates=sched_dates
		from sybmgmtdb..js_schedules where
			(@sched_arg   = 0 or sched_id = @sched_id) and
			( @all_arg = 1
			   or (@owner_arg = 0 and (sched_owner = @owner_val or (sched_properties & 32 = 32)) )
			   or (@owner_arg = 1 and sched_owner = @owner_val)
			)
		select @err=@@error, @rows=@@rowcount
		return @err
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_listschedule')
begin
	print 'Created sp_listschedule'
	grant execute on sp_listschedule to public
end
go
go
if exists (select name from sysobjects where name = 'sp_listjobtext')
	drop proc sp_listjobtext
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_listjobtext (
	@jname_id	univarchar(64),
	@option		univarchar(64) = NULL
)
as
begin
	declare @sp_name varchar(32), @tjname univarchar(64), @is_admin int
	declare @err int, @rows int, @msgno int, @job_id int, @properties int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_listjobtext'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the jname_id, as a name or as an id
	--
	select @tjname = rtrim(@jname_id)
	select @tjname = ltrim(@tjname)
	exec @job_id=sp_js_check_id @name_id=@tjname, @cmd=2, @table='job', @return_id=1, @is_admin=@is_admin
	if @job_id < 0
	begin
		select @msgno = abs(@job_id)
		raiserror @msgno, @sp_name, '@jname_id'
		return -@@error
	end
	--
	--
	--
	if @option = 'unichar' or @option = 'utf8'
		select substring(jcmd_text, 1, isnull(char_length(jcmd_text),1)-1)
			from sybmgmtdb..js_commands
			where jcmd_job_id=@job_id order by jcmd_seqno
	else
		select convert(varchar(1800), substring(jcmd_text, 1, isnull(char_length(jcmd_text),1)-1))
			from sybmgmtdb..js_commands
			where jcmd_job_id=@job_id order by jcmd_seqno

	return @@error
end
go
if exists (select name from sysobjects where name = 'sp_listjobtext')
begin
	print 'Created sp_listjobtext'
	grant execute on sp_listjobtext to public
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_controljob')
	drop proc sp_controljob
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_controljob (
	@sjname_id	univarchar(64)	= NULL,
	@jname_id	univarchar(64)	= NULL,
	@runid		univarchar(64)	= NULL,
	@option		univarchar(512)	= NULL
)
as
begin
	declare @name univarchar(128)
	declare @err int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1

	select @name=NULL
	if @sjname_id is not NULL	select @name='sjname=' + @sjname_id
	if @jname_id  is not NULL	select @name='jname='  + @jname_id
	if @runid     is not NULL	select @name='runid='  + @runid
	select @option='sp_name=sp_controljob,' + @option

	exec @err=sp_sjobcontrol @name=@name, @option=@option
	select return_code=@err
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_controljob')
begin
	print 'Created sp_controljob'
	grant execute on sp_controljob to js_user_role
	grant execute on sp_controljob to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_js_agent')
	drop proc sp_js_agent
go
--
-- Internal JobScheduler stored procedure (JS Agent)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_js_agent (
	@option		varchar(512)	= NULL
)
as
begin
	declare @value varchar(512), @opt_val_pair varchar(128), @opt_name varchar(32), @opt_value varchar(64)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int
	declare @err int, @rows int, @msgno int, @is_admin int, @id int, @size int, @sjob_id int, @id_needed int
	declare @cmd varchar(32), @state varchar(2), @id_value varchar(64), @table_name varchar(64), @sql varchar(512)
	declare @server varchar(30), @locale varchar(30), @user_run varchar(30), @user_req varchar(30)
	declare @properties int, @jproperties int, @default_timeout int, @timeout int, @id_ret int, @id_arg int
	declare @sp_name varchar(32), @id2_value varchar(64), @id2_arg int, @id2 int, @spid int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_js_agent'
	select	@id_arg =0, @id_needed =0, @id2_arg =0

	select @is_admin=proc_role('js_admin_role')
	select @value=ltrim(rtrim(@option))
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @len=isnull(char_length(@value), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @value)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @value=stuff(@value, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @value=stuff(@value, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@value, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0					-- @option=opt_name
		begin
			select @opt_name=ltrim(rtrim(@opt_val_pair)), @opt_value=NULL
		end
		else if @eq_pos = @opt_val_len			-- @property=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
			raiserror 19090, @sp_name, @option, @opt_val_pair
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end

		if @opt_name = 'runid_to_sjobid' or @opt_name = 'runid_to_jobid'
			or @opt_name = 'runid_to_schedid' or @opt_name = 'setend'
			or @opt_name = 'setstart'
		begin
			select @cmd=@opt_name, @table_name='jsh', @id_needed=1
		end
		else if @opt_name = 'conninfo'
		begin
			select @cmd=@opt_name, @table_name='sjob', @id_needed=1
		end
		else if @opt_name = 'sqlsize'
		begin
			select @cmd=@opt_name, @table_name='job', @id_needed=1
		end
		else if @opt_name = 'setstate'
		begin
			select @state=convert(varchar(2), @opt_value)
			if @state != 'W' and @state != 'Q' and @state != 'B' and
				@state != 'R1' and @state != 'R2' and @state != 'C1' and @state != 'C2' and 
				@state != 'T1' and @state != 'T2' and @state != 'X1' and @state != 'X2' and 
				@state != 'M'
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
				raiserror 19090, @sp_name, @option, @opt_name
				return -@@error
			end
			select @cmd=@opt_name, @id_needed = 1, @table_name='jsh'
		end
		else if @opt_name = 'setspid'
		begin
			select @spid=convert(int, @opt_value)
			select @id_needed=1, @table_name='jsh', @cmd='setspid'
		end
		else if @opt_name = 'id'
		begin
			select @id_value=@opt_value, @id_arg=1
		end
		else if @opt_name = 'id2'
		begin
			select @id2_value=@opt_value, @id2_arg=1, @id_needed=0
		end
		else if @opt_name = 'setsize'
		begin
			exec @size=sp_js_check_id @name_id=@opt_value, @cmd=3
			if @size < 0
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
				raiserror 19090, @sp_name, @option, @opt_name
				return -@@error
			end
			select @cmd=@opt_name, @id_needed=1, @table_name='jsh'
		end
		else if @opt_name = 'statelist'
		begin
			select @cmd=@opt_name, @table_name='jsh'
		end
		else if @opt_name = 'state'
		begin
			select @state=convert(varchar(2), @opt_value)
		end
		else if @opt_name = 'ids'
		begin
			--
			-- We must be js_admin_role and have specified the statelist command 
			-- and a state before the ids list.
			--
			if @is_admin = 0
			begin
				-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
				raiserror 19083, @sp_name, 'ids'
				return -@@error
			end
			if @cmd != 'statelist'
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
				raiserror 19090, @sp_name, @option, 'statelist'
				return -@@error
			end
			if @state is NULL
			begin
				-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
				raiserror 19090, @sp_name, @option, 'state'
				return -@@error
			end
			exec @id=sp_js_check_id @name_id=@opt_value, @cmd=1
			if @id < 0
			begin
				select @msgno = abs(@id)
				raiserror @msgno, @sp_name, @opt_value
				return -@@error
			end
			select jsh_exid from sybmgmtdb..js_history
				where jsh_state = @state and jsh_exid = @id
			select @err=@@error, @rows=@@rowcount
		end
		else if @cmd = 'statelist'
		begin
			-- For the statelist command, everything after ids is a runid
			exec @id=sp_js_check_id @name_id=@opt_name, @cmd=1
			if @id < 0
			begin
				select @msgno = abs(@id)
				raiserror @msgno, @sp_name, @opt_name
				return -@@error
			end
			select jsh_exid from sybmgmtdb..js_history
				where jsh_state = @state and jsh_exid = @id
			select @err=@@error, @rows=@@rowcount
		end
		else
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
			raiserror 19090, @sp_name, @option, @opt_val_pair
			return -@@error
		end
		
		select @curpos=@end_pos + 1
	end

	if @cmd = 'statelist'
	begin
		return @err
	end
	if @id_needed = 1
	begin
		exec @id=sp_js_check_id @name_id=@id_value, @cmd=1, @table=@table_name, @is_admin=@is_admin
		if @id < 0
		begin
			select @msgno = abs(@id)
			raiserror @msgno, @sp_name, @id_value
			return -@@error
		end
	end
	if @id2_arg = 1
	begin
		exec @id2=sp_js_check_id @name_id=@id2_value, @cmd=1, @table='jsh', @is_admin=@is_admin
		if @id2 < 0
		begin
			select @msgno = abs(@id2)
			raiserror @msgno, @sp_name, @id2_value
			return -@@error
		end
	end
	if @is_admin = 0
	begin
		-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
		raiserror 19083, @sp_name, 'js_agent'
		return -@@error
	end
	if @table_name = 'jsh'
	begin
		select @sjob_id=jsh_sjobid from sybmgmtdb..js_history where jsh_exid = @id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
			return @err
		if @rows != 1
		begin
			if @rows > 1
			begin
				-- 19086 'Procedure %1!, internal error duplicate rows with runid %2!, in table %3!.'
				raiserror 19086, @sp_name, @id, 'js_history'
				return -@@error
			end
			-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
			raiserror 19082, @sp_name, @option
			return -@@error
		end
		if @cmd = 'runid_to_sjobid'
			return @sjob_id
		select @id_ret=0, @err=0
		if @cmd = 'runid_to_jobid'
		begin
			select @id_ret=sjob_job_id from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
				return @err
			if @rows <= 0
			begin
				-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
				raiserror 19082, @sp_name, @option
				return -@@error
			end
			return @id_ret
		end
		if @cmd = 'runid_to_schedid'
		begin
			select @id_ret=sjob_sched_id from sybmgmtdb..js_scheduledjobs where sjob_id = @sjob_id
			select @err=@@error, @rows=@@rowcount
			if @err != 0
				return @err
			if @rows <= 0
			begin
				-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
				raiserror 19082, @sp_name, @option
				return -@@error
			end
			return @id_ret
		end
		if @cmd = 'setstate'
		begin
			update sybmgmtdb..js_history set jsh_state=@state where jsh_exid = @id
			select @err=@@error, @rows=@@rowcount
		end
		else if @cmd = 'setstart'
		begin
			update sybmgmtdb..js_history set jsh_jobstart=getdate() where jsh_exid = @id
			select @err=@@error, @rows=@@rowcount
		end
		else if @cmd = 'setend'
		begin
			update sybmgmtdb..js_history set jsh_jobend=getdate() where jsh_exid = @id
			select @err=@@error, @rows=@@rowcount
		end
		else if @cmd = 'setsize'
		begin
			update sybmgmtdb..js_history set jsh_size=@size where jsh_exid = @id
			select @err=@@error, @rows=@@rowcount
		end
		else if @cmd = 'setspid'
		begin
			update sybmgmtdb..js_history set jsh_spid=@spid where jsh_exid = @id
			select @err=@@error, @rows=@@rowcount
		end
		if @err != 0
		begin
			-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
			raiserror 19074, @sp_name, 'js_history', @err
			return -@@error
		end
		return @id_ret
	end
	else if @cmd = 'sqlsize'
	begin
		select @size=sum(isnull(char_length(jcmd_text),1)-1) from sybmgmtdb..js_commands where jcmd_job_id = @id
		select @err=@@error, @rows=@@rowcount
		select @size=isnull(@size, 0)
		if @err != 0
			return @err
		if @rows <= 0
		begin
			-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
			raiserror 19082, @sp_name, @option
			return -@@error

		end
		return @size
	end
	else if @cmd = 'conninfo'
	begin
		if @id2_arg = 1
		begin
			select @user_run=jsh_user_req, @id=jsh_sjobid from sybmgmtdb..js_history where jsh_exid=@id2
			select @err=@@error, @rows=@@rowcount
			if @err != 0
				return @err
			if @rows != 1
			begin
				-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
				raiserror 19082, @sp_name, @option
				return -@@error
			end
		end
		select @id_ret=sjob_job_id, @server=sjob_server, @locale=sjob_locale,
			@timeout=sjob_timeout_value, @user_req=sjob_owner, @properties=sjob_properties
			from sybmgmtdb..js_scheduledjobs where sjob_id=@id
		select @err=@@error, @rows=@@rowcount
		if @err != 0
			return @err
		if @rows != 1
		begin
			-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
			raiserror 19082, @sp_name, @option
			return -@@error
		end
		if @id2_arg = 1 select @user_req=@user_run

		select @jproperties=job_properties, @user_run=job_owner, @default_timeout=job_default_timeout
			from sybmgmtdb..js_jobs where job_id=@id_ret
		select @err=@@error, @rows=@@rowcount
		if @err != 0
			return @err
		if @rows != 1
		begin
			-- 19082 'Procedure %1!, parameter %2!, 
                        --the specified runid does not exist.'
			raiserror 19082, @sp_name, @option
			return -@@error
		end

                --mjm: this looks bad because JS FS says 0 means no timeout
                --below check prevents user from not having a timeout, 
                --doesn't it? Need to investigate
		if @timeout is NULL or @timeout = 0
			select @timeout=@default_timeout
		if @jproperties & 2 != 2
			select @user_run=@user_req

                --now get the user's name on the target server if the target 
                --is not the current server.
                --print 'target server is %1!', @server
                --print 'local server is %1!', @@servername
                if( @server != @@servername )
                begin
                    declare @rmt_user_name varchar(30)
                    select @rmt_user_name = object_cinfo 
                      from master..sysattributes
                     where class = 9 
                       and object_type = 'EL'
                       and suser_name(object)=@user_run
                       and object_info1 in (select srvid from master..sysservers 
                                            where srvnetname = @server 
                                              and srvclass is not null 
                                              and srvclass != 0)
                    --print 'local user name is %1!', @user_run
                    --print 'remote user name is %1!', @rmt_user_name
                    select @user_run = @rmt_user_name
                end

                -- what does this do? It sets the return values for the agent,
                -- these values show up in the job object in jsthread
		select server=@server, locale=@locale, timeout=@timeout
                     , user_run=@user_run, user_req=@user_req
                     , sjob_properties=@properties, job_properties=@jproperties
		return 0
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_agent')
begin
	print 'Created sp_js_agent'
	grant execute on sp_js_agent to js_user_role
	grant execute on sp_js_agent to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_listjobhistory')
	drop proc sp_listjobhistory
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_listjobhistory (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @err int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select @option='sp_name=sp_listjobhistory,' + @option
	exec @err=sp_sjobhistory @option=@option
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_listjobhistory')
begin
	print 'Created sp_listjobhistory'
	grant execute on sp_listjobhistory to public
end
go
go
if exists (select name from sysobjects where name = 'sp_dropjobhistory')
	drop proc sp_dropjobhistory
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_dropjobhistory (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @err int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select @option='sp_name=sp_dropjobhistory,' + @option
	exec @err=sp_sjobhistory @option=@option
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_dropjobhistory')
begin
	print 'Created sp_dropjobhistory'
	grant execute on sp_dropjobhistory to js_user_role
	grant execute on sp_dropjobhistory to js_admin_role
	grant execute on sp_dropjobhistory to js_client_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_dropjoboutput')
	drop proc sp_dropjoboutput
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_dropjoboutput (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @err int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select @option='sp_name=sp_dropjoboutput,' + @option
	exec @err=sp_sjobhistory @option=@option
	return @err
end
go
if exists (select name from sysobjects where name = 'sp_dropjoboutput')
begin
	print 'Created sp_dropjoboutput'
	grant execute on sp_dropjoboutput to js_user_role
	grant execute on sp_dropjoboutput to js_admin_role
	grant execute on sp_dropjoboutput to js_client_role
end
go
go
if exists (select name from sysobjects where name = 'sp_readjoboutput')
	drop proc sp_readjoboutput
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_readjoboutput (
	@runid		varchar(64)
)
as
begin
	declare @sp_name varchar(32), @user_name varchar(32)
	declare @err int, @rows int, @msgno int, @run_id int, @is_admin int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_readjoboutput'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the runid 
	--
	select @runid = ltrim(rtrim(@runid))
	exec @run_id=sp_js_check_id @name_id=@runid, @cmd=1, @table='jsout', @is_admin=@is_admin
	if @run_id < 0
	begin
		select @msgno = abs(@run_id)
		--
		-- Do not raise an error if it is just a case of no job output
		--
		select @runid = ltrim(rtrim(@runid))
		exec @run_id=sp_js_check_id @name_id=@runid, @cmd=1, @table='jsh', @is_admin=@is_admin
		if @run_id < 0
		begin
			raiserror @msgno, @sp_name, '@runid'
			return -@@error
		end
		return 0
	end
	--
	-- Must have js_admin_role role or the user who requested the job (jsh_user_req)
	--
	select @user_name=jsh_user_req from sybmgmtdb..js_history where jsh_exid=@run_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_history', @err
		return -@@error
	end
	if @rows = 0
	begin
		-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
		raiserror 19082, @sp_name, @runid
		return -@@error
	end
--	if @rows > 1
--	begin
--		-- 19086 'Procedure %1!, internal error duplicate rows with runid %2!, in table %3!.'
--		raiserror 19086, @sp_name, @run_id, 'js_history'
--		return -@@error
--	end
	if @is_admin = 0 and @user_name != suser_name()
	begin
		-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
		raiserror 19083, @sp_name, @run_id
		return -@@error
	end
	select substring(jsout_text, 1, isnull(char_length(jsout_text),1)-1) from sybmgmtdb..js_output
		where jsout_exid=@run_id order by jsout_seqno
	return @@error
end
go
if exists (select name from sysobjects where name = 'sp_readjoboutput')
begin
	print 'Created sp_readjoboutput'
	grant execute on sp_readjoboutput to js_user_role
	grant execute on sp_readjoboutput to js_admin_role
	grant execute on sp_readjoboutput to js_client_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_writejoboutput')
	drop proc sp_writejoboutput
go
--
-- Internal JobScheduler stored procedure (JS Agent)
--
create proc sp_writejoboutput (
	@runid		varchar(64),
	@output		univarchar(1800) = NULL
)
as
begin
	declare @sp_name varchar(32), @user_name varchar(32), @is_admin int, @chunk univarchar(901), @curpos int
	declare @err int, @rows int, @msgno int, @run_id int, @size int, @seqno int, @tot_size int, @max_size int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_writejoboutput'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate the runid and check it exists in js_history
	--
	select @runid = ltrim(rtrim(@runid))
	exec @run_id=sp_js_check_id @name_id=@runid, @cmd=1, @table='jsh', @is_admin=@is_admin
	if @run_id < 0
	begin
		select @msgno = abs(@run_id)
		raiserror @msgno, @sp_name, '@runid'
		return -@@error
	end
	--
	-- Update lock the history table entry for @run_id
	--
	begin tran sp_writejoboutput
	save  tran nested_tran
	update sybmgmtdb..js_history set jsh_update=@@spid where jsh_exid=@run_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_history', @err
		return -@@error
	end
	if @rows = 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
		raiserror 19082, @sp_name, @runid
		return -@@error
	end
	--
	-- Must have js_admin_role role or be the user who requested the job (jsh_user_req)
	--
	select @user_name=jsh_user_req, @tot_size=jsh_size from sybmgmtdb..js_history where jsh_exid=@run_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_history', @err
		return -@@error
	end
	if @rows < 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19082 'Procedure %1!, parameter %2!, the specified runid does not exist.'
		raiserror 19082, @sp_name, @runid
		return -@@error
	end
	if @rows > 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19086 'Procedure %1!, internal error duplicate rows with runid %2!, in table %3!.'
		raiserror 19086, @sp_name, @run_id, 'js_history'
		return -@@error
	end
	if @is_admin = 0 and @user_name != suser_name()
	begin
		rollback tran nested_tran
		commit tran
		-- 19084 'Procedure %1!, you do not have permission to modify information for the specified scheduled job, job, schedule or running job.'
		raiserror 19084, @sp_name
		return -@@error
	end
	--
	-- Now lookup @run_id to get the current seqno in js_output
	--
	select @seqno=max(jsout_seqno) from sybmgmtdb..js_output where jsout_exid = @run_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_output', @err
		return -@@error
	end
	if @seqno is NULL
		select @seqno=0, @tot_size=0
	else
		select @seqno=@seqno + 1
	select @size=isnull(char_length(@output), 0)
	--
	-- Check and enforce maximum output per job
	--
	select @tot_size=@tot_size + @size
	select @max_size = value from master..sysconfigures where name = 'maximum job output'
	if @max_size is NULL or @max_size = 0 or @tot_size <= @max_size
	begin
		--
		-- Store the next chunk of job output
		--
		select @curpos=1, @err=0
		while @curpos <= @size and @err = 0
		begin
			select @chunk=substring(@output, @curpos, 900) + char(10)
			insert into sybmgmtdb..js_output (jsout_exid, jsout_type, jsout_size, jsout_seqno, jsout_text)
				values (@run_id, 0, 900, @seqno, @chunk + char(10))
			select @err=@@error, @rows=@@rowcount
			select @seqno=@seqno+1, @curpos=@curpos + 900
		end
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_output', @err
			return -@@error
		end
	end
	--
	-- release the update lock and set the new total size
	--
	update sybmgmtdb..js_history set jsh_update=0, jsh_size=@tot_size where jsh_exid=@run_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_history', @err
		return -@@error
	end
	commit tran
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_writejoboutput')
begin
	print 'Created sp_writejoboutput'
	grant execute on sp_writejoboutput to js_user_role
	grant execute on sp_writejoboutput to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_createjobtemplate')
	drop proc sp_createjobtemplate
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_createjobtemplate (
	@jtname		univarchar(64),
	@jtversion	univarchar(16)	= NULL,
	@jtdesc		univarchar(128)	= NULL,
	@jtgrouppath	univarchar(128)	= NULL,
	@jtlanguage	univarchar(32)	= NULL
)
as
begin
	declare @sp_name varchar(32), @tname univarchar(64), @vcname varchar(64)
	declare @err int, @rows int, @msgno int, @jtmpl_id int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_createjobtemplate'
	--
	-- Validate the jtname, don't do a lookup check
	-- as name is not unique
	select @tname = ltrim(rtrim(@jtname))
	exec @jtmpl_id=sp_js_check_id @name_id=@tname, @cmd=0
	if @jtmpl_id < 0
	begin
		select @msgno = abs(@jtmpl_id)
		raiserror @msgno, @sp_name, '@jtname'
		return -@@error
	end
	if @jtlanguage is NULL select @jtlanguage='en'
	--
	select @jtmpl_id=jtmpl_id from sybmgmtdb..js_templates
		where jtmpl_name=@tname and jtmpl_version=@jtversion and jtmpl_language=@jtlanguage
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_templates', @err
		return -@@error
	end
	if @rows >= 1
	begin
		-- 19059 "Procedure %1!, a %2! entry already exists with the name %3!."
		select @vcname=@tname
		raiserror 19059, @sp_name, 'js_templates', @vcname
		return -@@error
	end
	--
	begin tran sp_createjobtemplate
	save tran nested_tran

	exec @jtmpl_id=sp_js_getkey 'jtmpl_id'
	if @jtmpl_id < 0
	begin
		rollback tran nested_tran
		commit tran
		select @msgno=abs(@jtmpl_id)
		raiserror @msgno, @sp_name, 'jtmpl_id'
		return -@@error
	end

	insert into sybmgmtdb..js_templates ( jtmpl_id, jtmpl_type, jtmpl_name, jtmpl_version,
		jtmpl_description, jtmpl_owner, jtmpl_created, jtmpl_group_path, jtmpl_update, jtmpl_language )
		values
		(@jtmpl_id, 0, @tname, @jtversion, @jtdesc, suser_name(), getdate(), @jtgrouppath, 0, @jtlanguage)
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
		raiserror 19075, @sp_name, 'js_templates', @err
		return -@@error
	end
	commit tran
	return @jtmpl_id
end
go
if exists (select name from sysobjects where name = 'sp_createjobtemplate')
begin
	print 'Created sp_createjobtemplate'
	grant execute on sp_createjobtemplate to js_user_role
	grant execute on sp_createjobtemplate to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_modifyjobtemplate')
	drop proc sp_modifyjobtemplate
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_modifyjobtemplate (
	@jtid		int		= NULL,
	@jtname		univarchar(64)	= NULL,
	@jtversion	univarchar(16)	= NULL,
	@jtnewname	univarchar(64)	= NULL,
	@jtnewversion	univarchar(16)	= NULL,
	@jtdesc		univarchar(128)	= NULL,
	@jtgrouppath	univarchar(128)	= NULL,
	@jtlanguage	univarchar(32)	= NULL,
	@jtnewlanguage	univarchar(32)	= NULL
)
as
begin
	declare @sp_name varchar(32), @tname univarchar(64), @owner varchar(30), @vcname varchar(64)
	declare @cur_jtversion univarchar(16), @cur_jtdesc univarchar(128), @cur_grouppath univarchar(128)
	declare @cur_jtlanguage univarchar(32)
	declare @err int, @rows int, @msgno int, @jtmpl_id int, @is_admin int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_modifyjobtemplate'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the jtname or id
	--
	select @tname = ltrim(rtrim(@jtname))
	if @jtlanguage is NULL select @jtlanguage='en'
	if @tname is not NULL
	begin
		select @jtmpl_id=jtmpl_id, @owner=jtmpl_owner, @cur_jtversion=jtmpl_version,
			@cur_jtdesc=jtmpl_description, @cur_grouppath=jtmpl_group_path,
			@cur_jtlanguage=jtmpl_language
		from sybmgmtdb..js_templates
		where jtmpl_name=@tname and jtmpl_version=@jtversion and jtmpl_language=@jtlanguage
		select @err=@@error, @rows=@@rowcount
	end
	else if @jtid is not NULL
	begin
		select @jtmpl_id=jtmpl_id, @owner=jtmpl_owner, @tname=jtmpl_name, @cur_jtversion=jtmpl_version,
			@cur_jtdesc=jtmpl_description, @cur_grouppath=jtmpl_group_path,
			@cur_jtlanguage=jtmpl_language
		from sybmgmtdb..js_templates where jtmpl_id=@jtid
		select @err=@@error, @rows=@@rowcount
	end
	else	select @err=0, @rows=0
	
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_templates', @err
		return -@@error
	end
	if @rows <= 0
	begin
		-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
		select @vcname=@jtname
		raiserror 19050, @sp_name, @vcname
		return -@@error
	end
	if @rows > 1
	begin
		-- 19097 "Procedure %1!, %2! is a non-unique name for a scheduledjob, job or schedule, the id value must be used."
		select @vcname=@jtname
		raiserror 19097, @sp_name, @vcname
		return -@@error
	end
	if @is_admin = 0 and @owner != suser_name()
	begin
		-- 19084 'Procedure %1!, you do not have permission to modify the scheduledjob, job, schedule or running job - %2!.'
		select @vcname=@jtname
		raiserror 19084, @sp_name, @vcname
		return -@@error
	end
	--
	if @jtnewversion is not NULL
		if @jtnewversion = @cur_jtversion select @jtnewversion=NULL
		else select @cur_jtversion=@jtnewversion
	if @jtnewname is not NULL
		if @jtnewname = @tname select @jtnewname=NULL
		else select @tname=@jtnewname
	if @jtnewlanguage is not NULL
		if @jtnewlanguage = @cur_jtlanguage select @jtnewlanguage=NULL
		else select @cur_jtlanguage=@jtnewlanguage
	if @jtdesc is not NULL		select @cur_jtdesc=@jtdesc
	if @jtgrouppath is not NULL	select @cur_grouppath=@jtgrouppath

	if ( @jtnewversion is not NULL or @jtnewname is not NULL or @jtnewlanguage is not NULL ) and
		exists ( select jtmpl_id from sybmgmtdb..js_templates
			where jtmpl_name=@tname and jtmpl_version = @cur_jtversion
				and jtmpl_language = @cur_jtlanguage )
	begin
		-- 19059 "Procedure %1!, a %2! entry already exists with the name %3!."
		select @vcname=@tname
		raiserror 19059, @sp_name, 'js_templates', @vcname
		return -@@error
	end

	update sybmgmtdb..js_templates set jtmpl_name=@tname, jtmpl_version=@cur_jtversion,
		jtmpl_description=@cur_jtdesc, jtmpl_group_path=@cur_grouppath, jtmpl_language=@cur_jtlanguage
		where jtmpl_id = jtmpl_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_templates', @err
		return -@@error
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_modifyjobtemplate')
begin
	print 'Created sp_modifyjobtemplate'
	grant execute on sp_modifyjobtemplate to js_user_role
	grant execute on sp_modifyjobtemplate to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_readjobtemplate')
	drop proc sp_readjobtemplate
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_readjobtemplate (
	@jtid		int		= NULL,
	@jtname		univarchar(64)	= NULL,
	@jtversion	univarchar(16)	= NULL,
	@jtlanguage	univarchar(32)	= NULL
)
as
begin
	declare @sp_name varchar(32), @tname univarchar(64), @vcname varchar(64)
	declare @err int, @rows int, @msgno int, @jtmpl_id int, @is_admin int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_readjobtemplate'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the jtname or id
	--
	select @tname = ltrim(rtrim(@jtname))
	if @jtlanguage is NULL select @jtlanguage='en'
	if @tname is not NULL
	begin
		select @jtmpl_id=jtmpl_id from sybmgmtdb..js_templates
			where jtmpl_name=@tname and jtmpl_version=@jtversion and jtmpl_language=@jtlanguage
		select @err=@@error, @rows=@@rowcount
	end
	else if @jtid is not NULL
	begin
		select @jtmpl_id=jtmpl_id from sybmgmtdb..js_templates where jtmpl_id=@jtid
		select @err=@@error, @rows=@@rowcount
	end
	else	select @err=0, @rows=0
	
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_templates', @err
		return -@@error
	end
	if @rows <= 0
	begin
		-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
		select @vcname=@jtname
		raiserror 19050, @sp_name, @vcname
		return -@@error
	end
	if @rows > 1
	begin
		-- 19097 "Procedure %1!, %2! is a non-unique name for a scheduledjob, job or schedule, the id value must be used."
		select @vcname=@jtname
		raiserror 19097, @sp_name, @vcname
		return -@@error
	end
	--
	--
	--
	select substring(jxml_text, 1, isnull(char_length(jxml_text),1)-1) from sybmgmtdb..js_xml
		where jxml_jtmpl_id=@jtmpl_id order by jxml_seqno
	return @@error
end
go
if exists (select name from sysobjects where name = 'sp_readjobtemplate')
begin
	print 'Created sp_readjobtemplate'
	grant execute on sp_readjobtemplate to js_user_role
	grant execute on sp_readjobtemplate to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_writejobtemplate')
	drop proc sp_writejobtemplate
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_writejobtemplate (
	@jtid		int		= NULL,
	@jtname		univarchar(64)	= NULL,
	@jtversion	univarchar(16)	= NULL,
	@text		univarchar(8000) = NULL,
	@jtlanguage	univarchar(32)	= NULL
)
as
begin
	declare @tname univarchar(64), @chunk univarchar(901), @owner varchar(30), @vcname varchar(64)
	declare @err int, @rows int, @msgno int, @jtmpl_id int, @seqno int, @curpos int, @len int, @is_admin int
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_writejobtemplate'
	select  @is_admin=proc_role('js_admin_role')
	--
	-- Validate and lookup the jtname or id
	--
	select @tname = ltrim(rtrim(@jtname))
	if @jtlanguage is NULL select @jtlanguage='en'
	if @tname is not NULL
	begin
		select @jtmpl_id=jtmpl_id, @owner=jtmpl_owner
		from sybmgmtdb..js_templates where jtmpl_name=@tname and jtmpl_version=@jtversion
		select @err=@@error, @rows=@@rowcount
	end
	else if @jtid is not NULL
	begin
		select @jtmpl_id=jtmpl_id, @owner=jtmpl_owner from sybmgmtdb..js_templates where jtmpl_id=@jtid
		select @err=@@error, @rows=@@rowcount
	end
	else	select @err=0, @rows=0
	
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_templates', @err
		return -@@error
	end
	if @rows <= 0
	begin
		-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
		select @vcname=@jtname
		raiserror 19050, @sp_name, @vcname
		return -@@error
	end
	if @rows > 1
	begin
		-- 19097 "Procedure %1!, %2! is a non-unique name for a scheduledjob, job or schedule, the id value must be used."
		select @vcname=@jtname
		raiserror 19097, @sp_name, @vcname
		return -@@error
	end

	begin tran sp_writejobtemplate
	save tran nested_tran
	--
	-- update lock the job
	--
	update sybmgmtdb..js_templates set jtmpl_update=@@spid where jtmpl_id = @jtmpl_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_templates', @err
		return -@@error
	end
	--
	-- Must be js_admin_role or own the job
	--
	if @is_admin = 0 and not exists (select jtmpl_id from sybmgmtdb..js_templates
					where jtmpl_id=@jtmpl_id and jtmpl_owner = suser_name())
	begin
		rollback tran nested_tran
		commit tran
		-- 19084 'Procedure %1!, you do not have permission to modify the specified scheduled job, job, schedule or running job.'
		raiserror 19084, @sp_name 
		return -@@error
	end
	select @seqno=max(jxml_seqno) from sybmgmtdb..js_xml where jxml_jtmpl_id = @jtmpl_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		rollback tran nested_tran
		commit tran
		-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
		raiserror 19075, @sp_name, 'js_xml', @err
		return -@@error
	end
	if @seqno is NULL
		select @seqno=0
	else
		select @seqno=@seqno+1
	select @curpos=1, @len=isnull(char_length(@text), 0)
	while @curpos <= @len
	begin
		select @chunk=substring(@text, @curpos, 900) + char(10)
		insert sybmgmtdb..js_xml (jxml_jtmpl_id, jxml_type, jxml_seqno, jxml_text)
			values (@jtmpl_id, 0, @seqno, @chunk)
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			rollback tran nested_tran
			commit tran
			-- 19075 'Procedure %1!, failed to insert an entry in the %2! table, insert error %3!.'
			raiserror 19075, @sp_name, 'js_xml', @err
			return -@@error
		end
		select @seqno=@seqno+1, @curpos=@curpos + 900
	end
	--
	-- release the update lock
	--
	update sybmgmtdb..js_templates set jtmpl_update=0 where jtmpl_id = @jtmpl_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0 or @rows != 1
	begin
		rollback tran nested_tran
		commit tran
		-- 19074 'Procedure %1!, failed to update an entry in the %2! table, update error %3!.'
		raiserror 19074, @sp_name, 'js_templates', @err
		return -@@error
	end
	commit tran
	return 0
end
go
--
--
if exists (select name from sysobjects where name = 'sp_writejobtemplate')
begin
	print 'Created sp_writejobtemplate'
	grant execute on sp_writejobtemplate to js_user_role
	grant execute on sp_writejobtemplate to js_admin_role
end
go
go
if exists (select name from sysobjects where name = 'sp_dropjobtemplate')
	drop proc sp_dropjobtemplate
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_dropjobtemplate (
	@jtid		int		= NULL,
	@jtname		univarchar(64)	= NULL,
	@jtversion	univarchar(16)	= NULL,
	@option		univarchar(512)	= NULL,
	@jtlanguage	univarchar(32)	= NULL
)
as
begin
	declare @opt_val_pair univarchar(512), @opt_name univarchar(512), @opt_value univarchar(512)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(64)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @tname univarchar(64), @all_users int, @xml_only int, @owner varchar(30)
	declare @err int, @rows int, @msgno int, @jtmpl_id int, @is_admin int
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_dropjobtemplate'
	select  @is_admin=proc_role('js_admin_role'), @all_users=0, @xml_only=0
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @option=ltrim(rtrim(@option))
	select @len=isnull(char_length(@option), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @option)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @option=stuff(@option, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @option=stuff(@option, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@option, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			select @opt_val_pair=ltrim(rtrim(@opt_val_pair))
			if @opt_val_pair = 'all_users'
			begin
				if @is_admin = 0
				begin
					-- 19077 "Procedure %1!, only a user with the role js_admin_role can specify the owner or all_users."
					raiserror 19077, @sp_name
					return -@@error
				end
				select @all_users=1, @curpos=@end_pos + 1
				continue
			end
			else if @opt_val_pair = 'xml_only'
			begin
				select @xml_only=1, @curpos=@end_pos + 1
				continue
			end
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		--
		if      @opt_name = 'all_users'	select @all_users=1
		else if @opt_name = 'xml_only'	select @xml_only=1
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
                	select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end

		select @curpos=@end_pos + 1
	end
	--
	-- Validate and lookup the jtname or id
	--
	select @tname = ltrim(rtrim(@jtname))
	if @jtlanguage is NULL select @jtlanguage='en'
	if @tname is not NULL
	begin
		select @jtmpl_id=jtmpl_id, @owner=jtmpl_owner
		from sybmgmtdb..js_templates where jtmpl_name=@tname and jtmpl_version=@jtversion
				and jtmpl_language=@jtlanguage
		select @err=@@error, @rows=@@rowcount
	end
	else if @jtid is not NULL
	begin
		select @jtmpl_id=jtmpl_id, @owner=jtmpl_owner
		from sybmgmtdb..js_templates where jtmpl_id=@jtid
		select @err=@@error, @rows=@@rowcount
	end
	else	select @err=0, @rows=0
	
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_templates', @err
		return -@@error
	end
	if @rows <= 0
	begin
		-- 19050 'Procedure %1!, parameter %2!, the specified job does not exist.'
		select @vcname=@jtname
		raiserror 19050, @sp_name, @vcname
		return -@@error
	end
	if @rows > 1
	begin
		-- 19097 "Procedure %1!, %2! is a non-unique name for a scheduledjob, job or schedule, the id value must be used."
		select @vcname=@jtname
		raiserror 19097, @sp_name, @vcname
		return -@@error
	end
	
	if @owner != suser_name() and @all_users = 0
	begin
		-- 19083 'Procedure %1!, you do not have permission to access the scheduledjob, job, schedule or running job - %2!.'
		select @vcname=@jtname
		raiserror 19083, @sp_name, @vcname
		return -@@error
	end

	delete from sybmgmtdb..js_xml where jxml_jtmpl_id = @jtmpl_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
		raiserror 19073, @sp_name, 'js_xml', @err
		return -@@error
	end
	if @xml_only = 1
		return 0

	delete from sybmgmtdb..js_templates where jtmpl_id = @jtmpl_id
	select @err=@@error, @rows=@@rowcount
	if @err != 0
	begin
		-- 19073 'Procedure %1!, failed to delete an entry from the %2! table, delete error %3!.'
		raiserror 19073, @sp_name, 'js_templates', @err
		return -@@error
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_dropjobtemplate')
begin
	print 'Created sp_dropjobtemplate'
	grant execute on sp_dropjobtemplate to js_user_role
	grant execute on sp_dropjobtemplate to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select name from sysobjects where name = 'sp_listjobtemplate')
	drop proc sp_listjobtemplate
go
--
-- Internal JobScheduler stored procedure (ASE Plugin)
--
-- Warning this procedure is not a published interface, do not use it.
--
create proc sp_listjobtemplate (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @opt_val_pair univarchar(512), @opt_name univarchar(512), @opt_value univarchar(512)
	declare @vcbuf1 varchar(512), @vcbuf2 varchar(512), @vcname varchar(64)
	declare @curpos int, @end_pos int, @eq_pos int, @len int, @opt_val_len int, @pos int
	declare @sp_name varchar(32), @jtname univarchar(64), @jtversion univarchar(16), @owner varchar(30)
	declare @jtlanguage univarchar(32), @jtdeflanguage univarchar(32)
	declare @err int, @rows int, @msgno int, @jtmpl_id int, @cmd univarchar(16), @is_admin int, @all_users int
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_listjobtemplate', @jtlanguage=NULL, @jtdeflanguage=NULL
	--
	-- Process the @option=<opt_name>=<opt_value>, list
	--
	select @option=ltrim(rtrim(@option))
	select @len=isnull(char_length(@option), 0), @curpos=1
	while @curpos < @len
	begin
		--
		-- get the end of the next pair: <opt_name>=<value>[,]
		--
		select @end_pos=patindex('%,%', @option)
		if @end_pos <= 0			-- single pair
			select @end_pos=@len + 1
		else if @end_pos = @curpos		-- extra ,
		begin
			select @option=stuff(@option, @end_pos, 1, ' '), @curpos=@curpos + 1
			continue
		end
		else	select @option=stuff(@option, @end_pos, 1, ' ')
		--
		-- Extract the opt_name=value pair
		--
		select @opt_val_pair=substring(@option, @curpos, @end_pos-@curpos)
		select @opt_val_len=isnull(char_length(@opt_val_pair), 0)
		--
		-- split the name and value
		--
		select @eq_pos=patindex('%=%', @opt_val_pair)
		if @eq_pos <= 0				-- @option=opt_name
		begin
			select @opt_val_pair=ltrim(rtrim(@opt_val_pair))
			if @opt_val_pair = 'all_users'
			begin
				select @all_users=1, @curpos=@end_pos + 1
				continue
			end
			else if @opt_val_pair  = 'list_ids'
			begin
				select @cmd='list_ids', @curpos=@end_pos + 1
				continue
			end
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else if @eq_pos = @opt_val_len		-- @option=opt_name=,  error
		begin
			-- 19090 'Procedure %1!, @option=''%2!'', %3! the option name or value is missing or invalid.'
                	select @vcbuf1=@option, @vcbuf2=@opt_val_pair
			raiserror 19090, @sp_name, @vcbuf1, @vcbuf2
			return -@@error
		end
		else
		begin
			select @opt_name=substring(@opt_val_pair, 1, @eq_pos-1)
			select @opt_name=ltrim(rtrim(@opt_name))

			select @opt_value=substring(@opt_val_pair, @eq_pos + 1, @opt_val_len)
			select @opt_value=ltrim(rtrim(@opt_value))
		end
		--
		if      @opt_name = 'jtid'
		begin
			exec @jtmpl_id=sp_js_check_id @name_id=@opt_value, @cmd=3
			if @jtmpl_id < 0
			begin
				select @msgno = abs(@jtmpl_id), @vcbuf1=@opt_value
				raiserror @msgno, @sp_name, @vcbuf1
				return -@@error
			end
		end
		else if @opt_name = 'jtname'
		begin
			select @jtname=@opt_value
		end
		else if @opt_name = 'jtversion'
		begin
			select @jtversion=@opt_value
		end
		else if @opt_name = 'jtlanguage'
		begin
			select @jtlanguage=@opt_value
			if @jtlanguage = @jtdeflanguage select @jtdeflanguage=NULL
		end
		else if @opt_name = 'jtdeflanguage'
		begin
			select @jtdeflanguage=@opt_value
			if @jtlanguage = @jtdeflanguage select @jtdeflanguage=NULL
		end
		else
		begin
			-- 19078 'Procedure %1!, unknown option (%2!).'
                	select @vcbuf1=@opt_name
			raiserror 19078, @sp_name, @vcbuf1
			return -@@error
		end

		select @curpos=@end_pos + 1
	end

	if @jtname is NULL and @jtmpl_id is NULL and @jtversion is NULL
	begin
		if @cmd = 'list_ids'
		begin
			if @jtlanguage is NULL or @jtlanguage = 'all'
			begin
				select jtmpl_id=jtmpl_id
				from sybmgmtdb..js_templates
				select @err=@@error, @rows=@@rowcount
			end
			else
			begin
				select jtmpl_id=jtmpl_id
				from sybmgmtdb..js_templates
				where jtmpl_language=@jtlanguage or jtmpl_language=@jtdeflanguage
				select @err=@@error, @rows=@@rowcount
			end
		end
		else if @jtlanguage is NULL
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path
			from sybmgmtdb..js_templates
			select @err=@@error, @rows=@@rowcount
		end
		else if @jtlanguage = 'all'
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			select @err=@@error, @rows=@@rowcount
		end
		else
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_language=@jtlanguage or jtmpl_language=@jtdeflanguage
			select @err=@@error, @rows=@@rowcount
		end
		if @err != 0
		begin
			-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
			raiserror 19076, @sp_name, 'js_templates', @err
			return -@@error
		end
		return 0
	end
	if @jtname is not NULL and @jtversion is not NULL
	begin
		if @jtlanguage is NULL
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path
			from sybmgmtdb..js_templates
			where jtmpl_name = @jtname and jtmpl_version = @jtversion
			select @err=@@error, @rows=@@rowcount
		end
		else if @jtlanguage = 'all'
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_name = @jtname and jtmpl_version = @jtversion
			select @err=@@error, @rows=@@rowcount
		end
		else
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_name = @jtname and jtmpl_version = @jtversion
				and ( jtmpl_language=@jtlanguage or jtmpl_language=@jtdeflanguage )
			select @err=@@error, @rows=@@rowcount
		end
	end
	else if @jtname is not NULL
	begin
		if @jtlanguage is NULL
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path
			from sybmgmtdb..js_templates
			where jtmpl_name = @jtname
			select @err=@@error, @rows=@@rowcount
		end
		else if @jtlanguage = 'all'
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_name = @jtname
			select @err=@@error, @rows=@@rowcount
		end
		else
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_name = @jtname
				and ( jtmpl_language=@jtlanguage or jtmpl_language=@jtdeflanguage )
			select @err=@@error, @rows=@@rowcount
		end

	end
	else if @jtversion is not NULL
	begin
		if @jtlanguage is NULL
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path
			from sybmgmtdb..js_templates
			where jtmpl_version = @jtversion
			select @err=@@error, @rows=@@rowcount
		end
		else if @jtlanguage = 'all'
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_version = @jtversion
			select @err=@@error, @rows=@@rowcount
		end
		else
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_version = @jtversion
				and ( jtmpl_language=@jtlanguage or jtmpl_language=@jtdeflanguage )
			select @err=@@error, @rows=@@rowcount
		end
	end
	else
	begin
		if @jtlanguage is NULL
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path
			from sybmgmtdb..js_templates
			where jtmpl_id = @jtmpl_id
			select @err=@@error, @rows=@@rowcount
		end
		else
		begin
			select jtmpl_id=jtmpl_id, jtmpl_name=jtmpl_name, jtmpl_version=jtmpl_version,
				jtmpl_description=jtmpl_description, jtmpl_owner=jtmpl_owner,
				jtmpl_created=jtmpl_created, jtmpl_group_path=jtmpl_group_path,
				jtmpl_language=jtmpl_language
			from sybmgmtdb..js_templates
			where jtmpl_id = @jtmpl_id
			select @err=@@error, @rows=@@rowcount
		end
	end
	
	if @err != 0
	begin
		-- 19076 'Procedure %1!, failed to read an entry in the %2! table, select error %3!.'
		raiserror 19076, @sp_name, 'js_templates', @err
		return -@@error
	end
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_listjobtemplate')
begin
	print 'Created sp_listjobtemplate'
	grant execute on sp_listjobtemplate to public
end
go
go
if exists (select name from sysobjects where name = 'sp_sjobclean')
	drop proc sp_sjobclean
go
--
--      Job Scheduler Client / Command Line Interface
--
--      sp_sjobclean  @option univarchar()
--
--      @option specfies either 'clean' or 'show'. The clean option deletes
--	job history and output based upon the Job Scheduler configuration
--	parameters:-
--		'percent database for history'
--		'percent history free'
--		'percent database for output'
--		'percent output free'
--		
--	The show option displays what sp_sjobclean 'clean' would try to delete
--	if the show option had not been given.
--
--	The sp_sjobclean procedure is only available to callers with the
--	roles js_admin_role or sa_role.
--
create proc sp_sjobclean (
	@option		univarchar(512)	= NULL
)
as
begin
	declare @err int, @rows int, @run_id int, @db_id int, @db_size int, @cmd_val varchar(16)
	declare @history_max int, @history_free int, @history_cur int, @history_target int, @history_count int
	declare @output_max int, @output_free int, @output_cur int, @output_target int, @output_count int
	declare @free_cur int, @free_target int, @do_clean int, @clean_count int, @loop_count int
	declare @history_start datetime, @history_rowtarget int, @history_clean int, @orphan_count int
	declare @output_start datetime, @output_rowtarget int, @output_clean int, @start datetime
	declare @sp_name varchar(32), @show varchar(1024)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_sjobclean'


	-- "Procedure %1!, the caller must have js_admin_role or sa_role role and be within the sybmgmtdb database."
	if ( proc_role('js_admin_role') = 0 and proc_role('sa_role') = 0 ) 
		or db_name() != 'sybmgmtdb'
	begin
		raiserror 19100, @sp_name
		return 0
	end
	if @option = 'clean' select @cmd_val = 'clean' else select @cmd_val = 'show'

	select @history_max  = value from master..sysconfigures where name = 'percent database for history'
	select @history_free = value from master..sysconfigures where name = 'percent history free'
	select @output_max   = value from master..sysconfigures where name = 'percent database for output'
	select @output_free  = value from master..sysconfigures where name = 'percent output free'
	--
	-- Setup default values when the parameters are not set
	--
	if @cmd_val = 'show'
	begin
		select @show='Configuration Parameters' + char(10)
		select @show=@show + '    percent database for history : '
		if @history_max  is NULL or @history_max  = 0
			select @show=@show + 'DEFAULT' + char(10)
		else
			select @show=@show + str(@history_max) + char(10)

		select @show=@show + '    percent database for output  : '
		if @output_max   is NULL or @output_max   = 0
			select @show=@show + 'DEFAULT' + char(10)
		else
			select @show=@show + str(@output_max) + char(10)

		select @show=@show + '    percent history free         : '
		if @history_free is NULL or @history_free = 0
			select @show=@show + 'DEFAULT' + char(10)
		else
			select @show=@show + str(@history_free) + char(10)

		select @show=@show + '    percent output free          : '
		if @output_free  is NULL or @output_free  = 0
			select @show=@show + 'DEFAULT' + char(10)
		else
			select @show=@show + str(@output_free) + char(10)
	end
	if @history_max  is NULL or @history_max  = 0 select @history_max  =20
	if @history_free is NULL or @history_free = 0 select @history_free =30
	if @output_max   is NULL or @output_max   = 0 select @output_max   =30
	if @output_free  is NULL or @output_free  = 0 select @output_free  =50
	--
	-- get the size of the data space, calculate the maximum space and the trimmed
	-- space for the history and output tables.
	--
	select @db_id=db_id('sybmgmtdb')
	select @db_size=sum(size) from master..sysusages where dbid = @db_id and ((segmap & 7) != 4)
	select @db_size=isnull(@db_size, 0)

	select @history_max    = (@db_size * @history_max) / 100
	select @history_target = (@history_max * (100 - @history_free)) / 100
	select @output_max     = (@db_size * @output_max) / 100
	select @output_target  = (@output_max * (100 - @output_free)) / 100
	--
	-- Calculate the free space
	--
	select @free_cur=sum(curunreservedpgs(dbid, lstart, unreservedpgs))
		from master..sysusages where dbid = @db_id and ((segmap & 7) != 4)
	select @free_cur=isnull(@free_cur, 0)
	select @free_target=@free_cur + 2 * @@thresh_hysteresis


	if @cmd_val = 'show'
	begin
		--
		-- Calculate the current reserved space and rowcount 
		-- in the history and output tables.
		--
		select @history_count=row_count(db_id(), id)
		from sybmgmtdb..sysindexes
		where id = object_id('js_history')
		  and indid <= 1
		
		/* See note tagged by NOTE_ABOUT_BUILT_INS in file 
                ** sproc/dbcc_run_configreport
                */
		select @history_cur=sum(case
					  when indid <= 1
					  then reserved_pages(db_id(), id, 
							      case 
								when indid = 1
								then 0
								else indid
							      end)
					  else 0
					end), 
		       @clean_count=sum(reserved_pages(db_id(), id, indid))
	        from sybmgmtdb..sysindexes 
		  where id = object_id('js_history')

		select @history_cur =  isnull(@history_cur, 0) 
				     + isnull(@clean_count, 0),
		       @history_count = isnull(@history_count, 0)
		
		select @output_count=row_count(db_id(), id)
		from sybmgmtdb..sysindexes
		where id = object_id('js_output')
		  and indid <= 1

		/* See note tagged by NOTE_ABOUT_BUILT_INS in file 
                ** sproc/dbcc_run_configreport
                */
		select @output_cur=sum(case
					 when indid <= 1
					 then reserved_pages(db_id(), id, 
							      case 
								when indid = 1
								then 0
								else indid
							      end)
					 else 0
				       end),
		       @clean_count=sum(reserved_pages(db_id(), id, indid))
		from sybmgmtdb..sysindexes 
                  where id = object_id('js_output')

		select @output_cur =  isnull(@output_cur, 0) 
				    + isnull(@clean_count, 0),
		       @output_count=isnull(@output_count, 0)
		--
		-- Calculate the target rowcounts in the history and output 
		-- tables.
		--
		if @history_cur > @history_target
		begin
			-- percent over the target
			select @history_rowtarget=((@history_cur - @history_target) * 100 ) / @history_max
			select @history_rowtarget = (@history_count * @history_rowtarget) / 100
		end
		else	select @history_rowtarget = 0
		--
		-- Count any job output that does not have a history entry and adjust the output_rowtarget
		--
		select @orphan_count=count(*) from sybmgmtdb..js_output j readpast
			where not exists ( select * from sybmgmtdb..js_history readpast where j.jsout_exid=jsh_exid)
		select @err=@@error, @rows=@@rowcount
		-- report select error, but continue
		--
		if @err != 0
		begin
			-- "Procedure %1!, failed to read an entry in the %2! table, select error %3!."
			raiserror 19076, @sp_name, 'js_history / js_output', @err
			select @orphan_count=0
		end
	
		if @output_cur > @output_target
		begin
			-- percent over the target
			select @output_rowtarget=((@output_cur - @output_target) * 100) / @output_max
			select @output_rowtarget=(@output_count * @output_rowtarget) / 100
			if @output_rowtarget >= @orphan_count
				select @output_rowtarget = @output_rowtarget - @orphan_count
			else select @output_rowtarget=0
		end
		else	select @output_rowtarget = 0

		select @show=@show + 
			'Database Sizes (pages)' + char(10) +
			'    data total       : ' + str(@db_size)        + char(10) +
			'    data free        : ' + str(@free_cur)       + char(10) +
			'    history current  : ' + str(@history_cur)    + char(10) +
			'    history target   : ' + str(@history_target) + char(10) +
			'    history maximum  : ' + str(@history_max)    + char(10) +
			'    output  current  : ' + str(@output_cur)     + char(10) +
			'    output  target   : ' + str(@output_target)  + char(10) +
			'    output  maximum  : ' + str(@output_max)     + char(10) +
			'Tables Sizes (rows)' + char(10) +
			'    history current  : ' + str(@history_count)  + char(10) +
			'    output  current  : ' + str(@output_count)   + char(10) +
			'sp_sjobclean ''clean'' would attempt to free approximately' + char(10) +
			'    history (rows)   : ' + str(@history_rowtarget)          + char(10) +
			'    output  (rows)   : ' + str(@output_rowtarget + @orphan_count)
		select @show
		return 0
	end

	select @do_clean=1, @history_clean=0, @output_clean=0, @loop_count=0, @clean_count=0
	while @do_clean > 0
	begin
		select @loop_count=@loop_count + 1
		select @clean_count=@clean_count + @history_clean + @output_clean
		if @loop_count = 1
		begin
			--
			-- Calculate the current and target rowcounts in the history and output tables.
			--
			select @history_count=row_count(db_id(), id)
		        from sybmgmtdb..sysindexes 
		        where id = object_id('js_history')
			  and indid <= 1

			select @history_count=isnull(@history_count, 0)
			select @history_rowtarget = (@history_count * (100 - @history_free)) / 100
	
			select @output_count=row_count(db_id(), id)
	 		from sybmgmtdb..sysindexes 
		 	where id = object_id('js_output')
			  and indid <= 1

			select @output_count=isnull(@output_count, 0)
			select @output_rowtarget = (@output_count * (100 - @output_free)) / 100

			-- print 'Procedure %1!, History (rows): current %2!, target %3!,  Output (rows): current %4!, target %5!,  Free space (pages): current %6!, target %7!.',
			--		@sp_name, @history_count, @history_rowtarget,
			--		@output_count, @output_rowtarget, @free_cur, @free_target
	    	end
	    	else
		begin
			--
			-- Calculate the current reserved space and rowcount 
			-- in the history and output tables.
			--

			select @history_count=row_count(db_id(), id)
			from sybmgmtdb..sysindexes
			where id = object_id('js_history')
			  and indid <= 1
		
			/* See note tagged by NOTE_ABOUT_BUILT_INS in file 
                        ** sproc/dbcc_run_configreport
                        */
			select @history_cur=sum(case
						  when indid <= 1
						  then reserved_pages(db_id(),
								      id, 
							      case 
								when indid = 1
								then 0 
								else indid
							      end)
						  else 0
						end),
			       @clean_count=sum(reserved_pages(db_id(), id, 
							       indid))
		        from sybmgmtdb..sysindexes 
                          where id = object_id('js_history')

			select @history_cur=isnull(@history_cur, 0) + isnull(@clean_count, 0),
					@history_count=isnull(@history_count, 0)
	
			select @output_count=row_count(db_id(), id)
			from sybmgmtdb..sysindexes
			where id = object_id('js_output')
			  and indid <= 1
			
			/* See note tagged by NOTE_ABOUT_BUILT_INS in file 
                        ** sproc/dbcc_run_configreport
                        */
			select @output_cur=sum(case 
						 when indid <= 1
						 then reserved_pages(db_id(), 
								     id, 
							      case 
								when indid = 1
								then 0
							      else indid
							end)
						 else 0
					       end), 
			       @clean_count=sum(reserved_pages(db_id(), id, 
							       indid))
	 	        from sybmgmtdb..sysindexes 
			where id = object_id('js_output')

			select @output_cur=isnull(@output_cur, 0) + isnull(@clean_count, 0),
					@output_count=isnull(@output_count, 0)
			--
			-- Calculate the current free space
			--
			select @free_cur=sum(curunreservedpgs(dbid, lstart, unreservedpgs))
				from master..sysusages where dbid = @db_id and ((segmap & 7) != 4)
				select @free_cur=isnull(@free_cur, 0)
--print 'loop %1!, free_cur %2!', @loop_count, @free_cur
			--
			-- if we didn't delete any rows in the last loop or we have looped too much, then stop.
			--
			if (@history_clean + @output_clean = 0) or @loop_count > 3
					break
			--
			-- If we are above the target reserved space, set the rowtargets to delete more
			--
			if @history_cur > @history_target 
				select @history_rowtarget = (@history_count * (100 - @history_free)) / 100
			else	select @history_rowtarget = 0
			if @output_cur > @output_target 
				select @output_rowtarget = (@output_count * (100 - @output_free)) / 100
			else	select @output_rowtarget = 0
--print 'loop N rows history count %1!, targ %2!,  output count %3!, targ %4!, @free_cur %5! targ %6!', 
--	@history_count, @history_rowtarget, @output_count, @output_rowtarget, @free_cur, @free_target
--print 'loop N history cur %1!, targ %2!,  output cur %3!, targ %4!, hcount %5!, ocount %6!',
--	@history_cur, @history_target, @output_cur, @output_target, @history_count, @output_count

			if @history_rowtarget = 0 and @output_rowtarget = 0
			begin
				--
				-- if the target free space has been reached stop. Otherwise clean
				-- again  - if there are rows left.
				--
				if @free_cur > @free_target
					break
				select @history_rowtarget = (@history_count * (100 - @history_free)) / 100
				select @output_rowtarget = (@output_count * (100 - @output_free)) / 100
				if @history_rowtarget = 0 and @output_rowtarget = 0
					break
			end
			select @history_clean=0, @output_clean=0
		end
		--
		-- Get the last jsh_jobstart for the target rows of history and output to be deleted.
		--
		if @output_rowtarget > 0
		begin
			set rowcount @output_rowtarget
			select @output_start=jsh_jobstart
				from sybmgmtdb..js_output readpast, sybmgmtdb..js_history readpast
				where jsout_exid = jsh_exid and jsh_update = 0
				order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
--print 'output err %1! rows %2! start %3!', @err, @rows, @output_start
			set rowcount 0
			if @err != 0
			begin
				-- "Procedure %1!, failed to read an entry in the %2! table, select error %3!."
				raiserror 19076, @sp_name, 'js_history', @err
				continue
			end
			if @rows = 0	 -- run out of rows that are not locked.
				select @output_start=NULL
		end
		if @history_rowtarget > 0
		begin
			set rowcount @history_rowtarget
			select @history_start=jsh_jobstart from sybmgmtdb..js_history readpast
				where jsh_update = 0 order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
--print 'history err %1! rows %2! start %3!', @err, @rows, @output_start
			set rowcount 0
			if @err != 0
			begin
				-- "Procedure %1!, failed to read an entry in the %2! table, select error %3!."
				raiserror 19076, @sp_name, 'js_history', @err
				continue
			end
			if @rows = 0	 -- run out of rows that are not locked.
				select @history_start=NULL
		end
		if @history_start is NULL and @output_start is NULL
			continue
		--
		-- Update lock on the latest of the dates
		--
		select @start=@history_start
		if @start is NULL		select @start=@output_start
		else if @output_start > @start	select @start=@output_start
		--
		update sybmgmtdb..js_history set jsh_update = @@spid
			from sybmgmtdb..js_history readpast
				where jsh_jobstart <= @start
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- "Procedure %1!, failed to update an entry in the %2! table, update error %3!."
			raiserror 19074, @sp_name, 'js_history', @err
			continue
		end
		if @rows = 0
			continue
		--
		-- First delete output based upon the latest date for cleaning history or output
		--
		delete from sybmgmtdb..js_output from sybmgmtdb..js_output readpast where jsout_exid in
				( select jsh_exid from sybmgmtdb..js_history readpast
					where jsh_update = @@spid and jsh_jobstart < @start )
		select @err=@@error, @rows=@@rowcount
		select @output_clean=@output_clean + @rows
--print 'output delete err %1!, rows %2!', @err, @rows
		if @err != 0
		begin
			-- "Procedure %1!, failed to delete an entry in the %2! table, delete error %3!."
			raiserror 19073, @sp_name, 'js_output', @err
		end
		--
		-- Now history based on the history date
		--
		delete from sybmgmtdb..js_history from sybmgmtdb..js_history readpast
				where jsh_update = @@spid and jsh_jobstart <= @history_start
		select @err=@@error, @history_clean=@@rowcount
--print 'history delete err %1!, rows %2!', @err, @history_clean
		if @err != 0
		begin
			-- "Procedure %1!, failed to delete an entry in the %2! table, delete error %3!."
			raiserror 19073, @sp_name, 'js_history', @err
		end
		--
		-- then remove any job output that does not have a history entry
		--
		delete from sybmgmtdb..js_output from sybmgmtdb..js_output j readpast
			where not exists ( select * from sybmgmtdb..js_history readpast
						where j.jsout_exid=jsh_exid)
		select @err=@@error, @rows=@@rowcount
		select @output_clean=@output_clean + @rows, @history_clean=0
--print 'output orphans err %1!, rows %2!', @err, @rows
		if @err != 0
		begin
			-- "Procedure %1!, failed to delete an entry in the %2! table, delete error %3!."
			raiserror 19073, @sp_name, 'js_output', @err
		end
	end
	--
	-- release any locks on entries we did not delete, e.g. no entry in the output
	--
	update sybmgmtdb..js_history set jsh_update = 0
		from sybmgmtdb..js_history readpast where jsh_update = @@spid

--print 'Done: history cur %1!, targ %2!,  output cur %3!, targ %4!, @free_cur %5! targ %6!, clean count %7!',
--	@history_cur, @history_target, @output_cur, @output_target, @free_cur, @free_target, @clean_count
--print 'Done: history count %1!, output count %2!', @history_count, @output_count

	-- 'Procedure %1!, History (rows): current %2!, target %3!,  Output (rows): current %4!, target %5!,  Free space (pages): current %6!, target %7!.'
	-- raiserror 19103, @sp_name, @history_count, @history_rowtarget,
	--					@output_count, @output_rowtarget, @free_cur, @free_target

	print 'Procedure %1!, after cleaning history and output the free space is %2! pages.', @sp_name, @free_cur
	return 0
end
go
if exists (select name from sysobjects where name = 'sp_sjobclean')
begin
	print 'Created sp_sjobclean'
	grant execute on sp_sjobclean to js_admin_role
end
go
go
dump transaction sybmgmtdb with truncate_only
go
if exists (select proc_name from systhresholds where proc_name = 'sp_js_history_thresh')
begin
	declare @free_space int
	select @free_space=free_space from systhresholds where proc_name = 'sp_js_history_thresh'
	exec sp_dropthreshold sybmgmtdb, 'default', @free_space
end
go
if exists (select name from sysobjects where name = 'sp_js_history_thresh')
	drop proc sp_js_history_thresh
go
--
--	Internal JobScheduler stored procedure
--
--      sp_js_history_thresh
--
--	This stored procedure is called automatically when the threshold of
--	free space in the default segment falls below 10%.
--
create proc sp_js_history_thresh (@dbname varchar(30), @segment_name varchar(30), @space_left int, @status int)
as
begin
	declare @err int, @rows int, @run_id int, @db_id int, @db_size int
	declare @history_max int, @history_free int, @history_cur int, @history_target int, @history_count int
	declare @output_max int, @output_free int, @output_cur int, @output_target int, @output_count int
	declare @free_cur int, @free_target int, @do_clean int, @clean_count int, @loop_count int
	declare @history_start datetime, @history_rowtarget int, @history_clean int
	declare @output_start datetime, @output_rowtarget int, @output_clean int, @start datetime
	declare @sp_name varchar(32)
	if @@trancount = 0
		set chained off
	set transaction isolation level 1
	select  @sp_name='sp_js_history_thresh'

	-- 'Procedure %1!, Warning the free data space threshold in database %2! has been exceeded.
	--  Segment %3! has %4! free pages, attempting to create space by cleaning job history and output.'
	raiserror 19099, @sp_name, @dbname, @segment_name, @space_left

	if @dbname != 'sybmgmtdb'
	begin
		-- 19100 'Procedure %1!, cannot be executed outside of the sybmgmtdb database.'
		raiserror 19100, @sp_name
		return 0
	end

	select @history_max  = value from master..sysconfigures where name = 'percent database for history'
	select @history_free = value from master..sysconfigures where name = 'percent history free'
	select @output_max   = value from master..sysconfigures where name = 'percent database for output'
	select @output_free  = value from master..sysconfigures where name = 'percent output free'
	--
	-- Setup default values when the parameters are not set
	--
	if @history_max  is NULL or @history_max  = 0 select @history_max  =20
	if @history_free is NULL or @history_free = 0 select @history_free =30
	if @output_max   is NULL or @output_max   = 0 select @output_max   =30
	if @output_free  is NULL or @output_free  = 0 select @output_free  =50
	--
	-- get the size of the data space, calculate the maximum space and the trimmed
	-- space for the history and output tables.
	--
	select @db_id=db_id('sybmgmtdb')
	select @db_size=sum(size) from master..sysusages where dbid = @db_id and ((segmap & 7) != 4)
	select @db_size=isnull(@db_size, 0)

	select @history_max    = (@db_size * @history_max) / 100
	select @history_target = (@history_max * (100 - @history_free)) / 100
	select @output_max     = (@db_size * @output_max) / 100
	select @output_target  = (@output_max * (100 - @output_free)) / 100
	--
	-- Calculate the target free space that is needed for the threshold to be activated again.
	--
	select @free_target=@space_left + 2 * @@thresh_hysteresis + 1

	select @do_clean=1, @history_clean=0, @output_clean=0, @loop_count=0, @clean_count=0
	while @do_clean > 0
	begin
		select @loop_count=@loop_count + 1
		select @clean_count=@clean_count + @history_clean + @output_clean
		if @loop_count = 1
		begin
			--
			-- Calculate the current and target rowcounts in the history and output tables.
			--
			select @history_count=row_count(db_id(), id)
		 	from sybmgmtdb..sysindexes 
			where id = object_id('js_history')
			  and indid <= 1

			select @history_count=isnull(@history_count, 0)
			select @history_rowtarget = (@history_count * (100 - @history_free)) / 100
	
			select @output_count=row_count(db_id(), id)
	 		from sybmgmtdb..sysindexes 
			where id = object_id('js_output')
			  and indid <= 1

			select @output_count=isnull(@output_count, 0)
			select @output_rowtarget = (@output_count * (100 - @output_free)) / 100

			-- 'Procedure %1!, History (rows): current %2!, target %3!,  Output (rows): current %4!, target %5!,  Free space (pages): current %6!, target %7!.'
			raiserror 19103, @sp_name, @history_count, @history_rowtarget,
						@output_count, @output_rowtarget, @space_left, @free_target
	    	end
	    	else
		begin
			--
			-- Calculate the current reserved space and rowcount in the history and output tables.
			--

			select @history_count=row_count(db_id(), id)
			from sybmgmtdb..sysindexes
			where id = object_id('js_history')
			  and indid <= 1
			
			/* See note tagged by NOTE_ABOUT_BUILT_INS in file 
        		** sproc/dbcc_run_configreport
        		*/
			select @history_cur=sum(case
						  when indid <= 1
						  then reserved_pages(db_id(),
								      id, 
							      case 
								when indid = 1
								then 0
								else indid
							      end)
						  else 0
						end),
			       @clean_count=sum(reserved_pages(db_id(), id, 
							       indid))
		 	from sybmgmtdb..sysindexes 
			  where id = object_id('js_history')

			select @history_cur=isnull(@history_cur, 0) + isnull(@clean_count, 0),
					@history_count=isnull(@history_count, 0)
	
			select @output_count=row_count(db_id(), id)
			from sybmgmtdb..sysindexes
			where id = object_id('js_history')
			  and indid <= 1

			/* See note tagged by NOTE_ABOUT_BUILT_INS in file 
                        ** sproc/dbcc_run_configreport
                        */
			select @output_cur=sum(case 
						 when indid <= 1
						 then reserved_pages(db_id(), 
								     id, 
							      case 
								 when indid = 1
								 then 0
								 else indid
							      end)
						  else 0
						end),
			       @clean_count=sum(reserved_pages(db_id(), id, 
							       indid))
	 		from sybmgmtdb..sysindexes 
			  where id = object_id('js_output')


			select @output_cur=isnull(@output_cur, 0) + isnull(@clean_count, 0),
					@output_count=isnull(@output_count, 0)
			--
			-- Calculate the current free space
			--
			select @free_cur=sum(curunreservedpgs(dbid, lstart, unreservedpgs))
				from master..sysusages where dbid = @db_id and ((segmap & 7) != 4)
				select @free_cur=isnull(@free_cur, 0)
--print 'loop %1!, free_cur %2!', @loop_count, @free_cur
			--
			-- if we didn't delete any rows in the last loop or we have looped too much, then stop.
			--
			if (@history_clean + @output_clean = 0) or @loop_count > 3
					break
			--
			-- If we are above the target reserved space, set the rowtargets to delete more
			--
			if @history_cur > @history_target 
				select @history_rowtarget = (@history_count * (100 - @history_free)) / 100
			else	select @history_rowtarget = 0
			if @output_cur > @output_target 
				select @output_rowtarget = (@output_count * (100 - @output_free)) / 100
			else	select @output_rowtarget = 0
--print 'loop N rows history count %1!, targ %2!,  output count %3!, targ %4!, @free_cur %5! targ %6!', 
--	@history_count, @history_rowtarget, @output_count, @output_rowtarget, @space_left, @free_target
--print 'loop N history cur %1!, targ %2!,  output cur %3!, targ %4!, hcount %5!, ocount %6!',
--	@history_cur, @history_target, @output_cur, @output_target, @history_count, @output_count

			if @history_rowtarget = 0 and @output_rowtarget = 0
			begin
				--
				-- if the target free space has been reached stop. Otherwise clean
				-- again  - if there are rows left.
				--
				if @free_cur > @free_target
					break
				select @history_rowtarget = (@history_count * (100 - @history_free)) / 100
				select @output_rowtarget = (@output_count * (100 - @output_free)) / 100
				if @history_rowtarget = 0 and @output_rowtarget = 0
					break
			end
			select @history_clean=0, @output_clean=0
		end
		--
		-- Get the last jsh_jobstart for the target rows of history and output to be deleted.
		--
		if @output_rowtarget > 0
		begin
			set rowcount @output_rowtarget
			select @output_start=jsh_jobstart
				from sybmgmtdb..js_output readpast, sybmgmtdb..js_history readpast
				where jsout_exid = jsh_exid and jsh_update = 0
				order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
--print 'output err %1! rows %2! start %3!', @err, @rows, @output_start
			set rowcount 0
			if @err != 0
			begin
				-- "Procedure %1!, failed to read an entry in the %2! table, select error %3!."
				raiserror 19076, @sp_name, 'js_history', @err
				continue
			end
			if @rows = 0	 -- run out of rows that are not locked.
				select @output_start=NULL
		end
		if @history_rowtarget > 0
		begin
			set rowcount @history_rowtarget
			select @history_start=jsh_jobstart from sybmgmtdb..js_history readpast
				where jsh_update = 0 order by jsh_jobstart asc
			select @err=@@error, @rows=@@rowcount
--print 'history err %1! rows %2! start %3!', @err, @rows, @output_start
			set rowcount 0
			if @err != 0
			begin
				-- "Procedure %1!, failed to read an entry in the %2! table, select error %3!."
				raiserror 19076, @sp_name, 'js_history', @err
				continue
			end
			if @rows = 0	 -- run out of rows that are not locked.
				select @history_start=NULL
		end
		if @history_start is NULL and @output_start is NULL
			continue
		--
		-- Update lock on the latest of the dates
		--
		select @start=@history_start
		if @start is NULL		select @start=@output_start
		else if @output_start > @start	select @start=@output_start
		--
		update sybmgmtdb..js_history set jsh_update = @@spid
			from sybmgmtdb..js_history readpast
				where jsh_jobstart <= @start
		select @err=@@error, @rows=@@rowcount
		if @err != 0
		begin
			-- "Procedure %1!, failed to update an entry in the %2! table, update error %3!."
			raiserror 19074, @sp_name, 'js_history', @err
			continue
		end
		if @rows = 0
			continue
		--
		-- First delete output based upon the latest date for cleaning history or output
		--
		delete from sybmgmtdb..js_output from sybmgmtdb..js_output readpast where jsout_exid in
				( select jsh_exid from sybmgmtdb..js_history readpast
					where jsh_update = @@spid and jsh_jobstart < @start )
		select @err=@@error, @rows=@@rowcount
		select @output_clean=@output_clean + @rows
--print 'output delete err %1!, rows %2!', @err, @rows
		if @err != 0
		begin
			-- "Procedure %1!, failed to delete an entry in the %2! table, delete error %3!."
			raiserror 19073, @sp_name, 'js_output', @err
		end
		--
		-- Now history based on the history date
		--
		delete from sybmgmtdb..js_history from sybmgmtdb..js_history readpast
				where jsh_update = @@spid and jsh_jobstart <= @history_start
		select @err=@@error, @history_clean=@@rowcount
--print 'history delete err %1!, rows %2!', @err, @history_clean
		if @err != 0
		begin
			-- "Procedure %1!, failed to delete an entry in the %2! table, delete error %3!."
			raiserror 19073, @sp_name, 'js_history', @err
		end
		--
		-- then remove any job output that does not have a history entry
		--
		delete from sybmgmtdb..js_output from sybmgmtdb..js_output j readpast
			where not exists ( select * from sybmgmtdb..js_history readpast
						where j.jsout_exid=jsh_exid)
		select @err=@@error, @rows=@@rowcount
		select @output_clean=@output_clean + @rows, @history_clean=0
--print 'output orphans err %1!, rows %2!', @err, @rows
		if @err != 0
		begin
			-- "Procedure %1!, failed to delete an entry in the %2! table, delete error %3!."
			raiserror 19073, @sp_name, 'js_output', @err
		end
	end
	--
	-- release any locks on entries we did not delete, e.g. no entry in the output
	--
	update sybmgmtdb..js_history set jsh_update = 0
		from sybmgmtdb..js_history readpast where jsh_update = @@spid

--print 'Done: history cur %1!, targ %2!,  output cur %3!, targ %4!, @free_cur %5! targ %6!, clean count %7!',
--	@history_cur, @history_target, @output_cur, @output_target, @free_cur, @free_target, @clean_count
--print 'Done: history count %1!, output count %2!', @history_count, @output_count

	-- 'Procedure %1!, History (rows): current %2!, target %3!,  Output (rows): current %4!, target %5!,  Free space (pages): current %6!, target %7!.'
	-- raiserror 19103, @sp_name, @history_count, @history_rowtarget,
	--					@output_count, @output_rowtarget, @space_left, @free_target

	-- 19101 'Procedure %1!, after cleaning history and output the free space is %1!.'
	raiserror 19101, @sp_name, @free_cur
	if @free_cur <= @free_target
	begin
		-- 19102 'Procedure %1!, WARNING: at least %2! free space is needed. Intervention is required to create space in the database.'
		raiserror 19102, @sp_name, @free_target
	end

	return 0
end
go
if exists (select name from sysobjects where name = 'sp_js_history_thresh')
begin
	print 'Created sp_js_history_thresh'
	grant execute on sp_js_history_thresh to js_admin_role
	--
	--	calculate 90% of the data space
	--
	declare @db_size int, @n int
	select @db_size=sum(size) from master.dbo.sysusages
		where dbid = db_id('sybmgmtdb') and ((segmap & 7) != 4)
	select @db_size=isnull(@db_size, 0)
	select @n=(@db_size * 10) / 100
	print 'Database data is %1! pages, installing free data threshold %2! pages, sp_js_history_thresh',
			@db_size, @n
	exec sp_addthreshold sybmgmtdb, "default", @n, sp_js_history_thresh
end
go
go
dump tran sybmgmtdb with truncate_only
go
dump tran tempdb with truncate_only
go
declare @tempdbname varchar(30)
select @tempdbname = db_name(@@tempdbid)
if (@tempdbname != 'tempdb')
begin
	dump tran @tempdbname with truncate_only
end
go
print 'Loading of sybmgmtdb database is complete.'
go

declare @retval int
exec @retval = sp_version 'installjsdb', NULL, '15.5/EBF 17340 SMP/P/x86_64/Enterprise Linux/ase155/2391/64-bit/OPT/Mon Nov  9 14:15:35 2009', 'end'
if (@retval != 0) select syb_quit()
go

