SQL Query not producing 'Disabled' jobs within the results, alongside 'Failed' jobs - sql

I have the following code for a SQL Query I'm working on..
DECLARE #Date datetime
SET #Date = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
DECLARE #jobHistory TABLE
(
job_id UNIQUEIDENTIFIER
, success INT
, cancel INT
, fail INT
, retry INT
, last_execution_id INT
, last_duration CHAR(8)
, last_execution_start DATETIME
);
WITH lastExecution
AS
(
SELECT job_id
, MAX(instance_id) AS last_instance_id
FROM msdb.dbo.sysjobhistory
WHERE step_id = 0
GROUP BY job_id
)
INSERT INTO #jobHistory
SELECT sjh.job_id
, SUM(CASE WHEN sjh.run_status = 1 AND step_id = 0 THEN 1 ELSE 0 END) AS success
, SUM(CASE WHEN sjh.run_status = 3 AND step_id = 0 THEN 1 ELSE 0 END) AS cancel
, SUM(CASE WHEN sjh.run_status = 0 AND step_id = 0 THEN 1 ELSE 0 END) AS fail
, SUM(CASE WHEN sjh.run_status = 2 THEN 1 ELSE 0 END) AS retry
, MAX(CASE WHEN sjh.step_id = 0 THEN instance_id ELSE NULL END) last_execution_id
, SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),2,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),4,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),6,2)
AS last_duration
, MAX(CASE WHEN le.last_instance_id IS NOT NULL THEN
CONVERT(datetime, RTRIM(run_date))
+ ((run_time / 10000 * 3600)
+ ((run_time % 10000) / 100 * 60)
+ (run_time % 10000) % 100) / (86399.9964)
ELSE '1900-01-01' END) AS last_execution_start
FROM msdb.dbo.sysjobhistory AS sjh
LEFT JOIN lastExecution AS le
ON sjh.job_id = le.job_id
AND sjh.instance_id = le.last_instance_id
GROUP BY sjh.job_id;
DECLARE #weekDay TABLE (
mask INT
, maskValue VARCHAR(32)
);
INSERT INTO #weekDay
SELECT 1, 'Sunday' UNION ALL
SELECT 2, 'Monday' UNION ALL
SELECT 4, 'Tuesday' UNION ALL
SELECT 8, 'Wednesday' UNION ALL
SELECT 16, 'Thursday' UNION ALL
SELECT 32, 'Friday' UNION ALL
SELECT 64, 'Saturday';
WITH myCTE
AS(
SELECT sched.name AS 'scheduleName'
, sched.schedule_id
, jobsched.job_id
, CASE
WHEN sched.freq_type = 1
THEN 'Once'
WHEN sched.freq_type = 4
AND sched.freq_interval = 1
THEN 'Daily'
WHEN sched.freq_type = 4
THEN 'Every ' + CAST(sched.freq_interval AS VARCHAR(5)) + ' days'
WHEN sched.freq_type = 8 THEN
REPLACE( REPLACE( REPLACE((
SELECT maskValue
FROM #weekDay AS x
WHERE sched.freq_interval & x.mask <> 0
ORDER BY mask FOR XML RAW)
, '"/><row maskValue="', ', '), '<row maskValue="', ''), '"/>', '')
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; weekly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' weeks' END
WHEN sched.freq_type = 16 THEN 'On day '
+ CAST(sched.freq_interval AS VARCHAR(10)) + ' of every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
WHEN sched.freq_type = 32 THEN
CASE
WHEN sched.freq_relative_interval = 1 THEN 'First'
WHEN sched.freq_relative_interval = 2 THEN 'Second'
WHEN sched.freq_relative_interval = 4 THEN 'Third'
WHEN sched.freq_relative_interval = 8 THEN 'Fourth'
WHEN sched.freq_relative_interval = 16 THEN 'Last'
END +
CASE
WHEN sched.freq_interval = 1 THEN ' Sunday'
WHEN sched.freq_interval = 2 THEN ' Monday'
WHEN sched.freq_interval = 3 THEN ' Tuesday'
WHEN sched.freq_interval = 4 THEN ' Wednesday'
WHEN sched.freq_interval = 5 THEN ' Thursday'
WHEN sched.freq_interval = 6 THEN ' Friday'
WHEN sched.freq_interval = 7 THEN ' Saturday'
WHEN sched.freq_interval = 8 THEN ' Day'
WHEN sched.freq_interval = 9 THEN ' Weekday'
WHEN sched.freq_interval = 10 THEN ' Weekend'
END
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; monthly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
END
WHEN sched.freq_type = 64 THEN 'StartUp'
WHEN sched.freq_type = 128 THEN 'Idle'
END AS 'frequency'
, ISNULL('Every ' + CAST(sched.freq_subday_interval AS VARCHAR(10)) +
CASE
WHEN sched.freq_subday_type = 2 THEN ' seconds'
WHEN sched.freq_subday_type = 4 THEN ' minutes'
WHEN sched.freq_subday_type = 8 THEN ' hours'
END, 'Once') AS 'subFrequency'
, REPLICATE('0', 6 - LEN(sched.active_start_time))
+ CAST(sched.active_start_time AS VARCHAR(6)) AS 'startTime'
, REPLICATE('0', 6 - LEN(sched.active_end_time))
+ CAST(sched.active_end_time AS VARCHAR(6)) AS 'endTime'
, REPLICATE('0', 6 - LEN(jobsched.next_run_time))
+ CAST(jobsched.next_run_time AS VARCHAR(6)) AS 'nextRunTime'
, CAST(jobsched.next_run_date AS CHAR(8)) AS 'nextRunDate'
FROM msdb.dbo.sysschedules AS sched
JOIN msdb.dbo.sysjobschedules AS jobsched
ON sched.schedule_id = jobsched.schedule_id
WHERE sched.enabled = 1
)
SELECT job.name AS [Job Name]
, CASE WHEN job.enabled = 1 THEN 'Enabled' ELSE 'Disabled' END AS [Job Status]
, COALESCE(sched.subFrequency, '') AS [Frequency]
, COALESCE(jh.last_duration, '') AS [Last Run Duration]
, COALESCE(jh.last_execution_start, '') AS [Last Run Time/Date]
FROM msdb.dbo.sysjobs AS job
LEFT JOIN myCTE AS sched
ON job.job_id = sched.job_id
LEFT JOIN #jobHistory AS jh
ON job.job_id = jh.job_id
WHERE jh.last_execution_start >= DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
AND job.name like '%MAINTENANCE - BACKUP%'
ORDER BY nextRunDate;
but although the results show the expected 'Failed' jobs, the 'Disabled' jobs are missing. I have also had help with this, as I have no SQL experience.
This Query has been created to check the Job History of roughtly 5/10 Backup Jobs within a 24 hour period, noting all the Failures (even if the last Run Succeeded). The seconds on the [Last Run Time/Date] also seem to be off, showing as soemthign like '50:00.0'
I also need a new column for the [Last Run Outcome] - to show if the Job 'Failed/Succeeded' as a Status.
Please let me know if you require any further information or a PasteBin of my code.

Related

Replace Bit Values (1) with Day names SQL

with following query i select days (bit values) from my database into a string separated with blank space:
SELECT CONVERT(VARCHAR(20),BPL_MONDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_TUESDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_WEDNESDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_THURSDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_FRIDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_SATURDAY) + ' ' +
CONVERT(VARCHAR(20),BPL_SUNDAY)
FROM BOS_PRICE_LIST
Result of the query looks something like this:
Now i want to replace 1 with current day name. Example of one row:
Current query result: 1 1 1 1 1 0 0
What i want: Monday Tuesday Wednesday Thursday Friday
Thanks for help
Greetings
Use CASE statement
SELECT case when BPL_MONDAY = 1 then 'Monday' else '' end +
case when BPL_TUESDAY = 1 then 'Tuesday' else '' end +
case when BPL_WEDNESDAY = 1 then 'Wednesday' else '' end +
case when BPL_THURSDAY = 1 then 'Thursday' else '' end +
case when BPL_FRIDAY = 1 then 'Friday' else '' end +
case when BPL_SATURDAY = 1 then 'Saturday' else '' end +
case when BPL_SUNDAY = 1 then 'Sunday' else '' end
FROM BOS_PRICE_LIST

How to get the SQL Server job schdule in a readable format?

On SQL Server 2008, each job under sql agent can have a schedule. I can get the data from these 2 tables:
sysjobs
sysschedules
How do I use SQL to get the schedule data in readable format? For example, display it as:
Job Name, Daily + time
or
Job Name, Weekly + time
This may be a bit beyond the scope of what you're looking for however this script from Michelle Ufford should be way beyond what you need.
I'm also posting the code on the off chance the blog disappears.
Declare #weekDay Table (
mask int
, maskValue varchar(32)
);
Insert Into #weekDay
Select 1, 'Sunday' Union All
Select 2, 'Monday' Union All
Select 4, 'Tuesday' Union All
Select 8, 'Wednesday' Union All
Select 16, 'Thursday' Union All
Select 32, 'Friday' Union All
Select 64, 'Saturday';
With myCTE
As(
Select sched.name As 'scheduleName'
, sched.schedule_id
, jobsched.job_id
, Case When sched.freq_type = 1 Then 'Once'
When sched.freq_type = 4
And sched.freq_interval = 1
Then 'Daily'
When sched.freq_type = 4
Then 'Every ' + Cast(sched.freq_interval As varchar(5)) + ' days'
When sched.freq_type = 8 Then
Replace( Replace( Replace((
Select maskValue
From #weekDay As x
Where sched.freq_interval & x.mask <> 0
Order By mask For XML Raw)
, '"/><row maskValue="', ', '), '<row maskValue="', ''), '"/>', '')
+ Case When sched.freq_recurrence_factor <> 0
And sched.freq_recurrence_factor = 1
Then '; weekly'
When sched.freq_recurrence_factor <> 0 Then '; every '
+ Cast(sched.freq_recurrence_factor As varchar(10)) + ' weeks' End
When sched.freq_type = 16 Then 'On day '
+ Cast(sched.freq_interval As varchar(10)) + ' of every '
+ Cast(sched.freq_recurrence_factor As varchar(10)) + ' months'
When sched.freq_type = 32 Then
Case When sched.freq_relative_interval = 1 Then 'First'
When sched.freq_relative_interval = 2 Then 'Second'
When sched.freq_relative_interval = 4 Then 'Third'
When sched.freq_relative_interval = 8 Then 'Fourth'
When sched.freq_relative_interval = 16 Then 'Last'
End +
Case When sched.freq_interval = 1 Then ' Sunday'
When sched.freq_interval = 2 Then ' Monday'
When sched.freq_interval = 3 Then ' Tuesday'
When sched.freq_interval = 4 Then ' Wednesday'
When sched.freq_interval = 5 Then ' Thursday'
When sched.freq_interval = 6 Then ' Friday'
When sched.freq_interval = 7 Then ' Saturday'
When sched.freq_interval = 8 Then ' Day'
When sched.freq_interval = 9 Then ' Weekday'
When sched.freq_interval = 10 Then ' Weekend'
End
+ Case When sched.freq_recurrence_factor <> 0
And sched.freq_recurrence_factor = 1 Then '; monthly'
When sched.freq_recurrence_factor <> 0 Then '; every '
+ Cast(sched.freq_recurrence_factor As varchar(10)) + ' months' End
When sched.freq_type = 64 Then 'StartUp'
When sched.freq_type = 128 Then 'Idle'
End As 'frequency'
, IsNull('Every ' + Cast(sched.freq_subday_interval As varchar(10)) +
Case When sched.freq_subday_type = 2 Then ' seconds'
When sched.freq_subday_type = 4 Then ' minutes'
When sched.freq_subday_type = 8 Then ' hours'
End, 'Once') As 'subFrequency'
, Replicate('0', 6 - Len(sched.active_start_time))
+ Cast(sched.active_start_time As varchar(6)) As 'startTime'
, Replicate('0', 6 - Len(sched.active_end_time))
+ Cast(sched.active_end_time As varchar(6)) As 'endTime'
, Replicate('0', 6 - Len(jobsched.next_run_time))
+ Cast(jobsched.next_run_time As varchar(6)) As 'nextRunTime'
, Cast(jobsched.next_run_date As char(8)) As 'nextRunDate'
From msdb.dbo.sysschedules As sched
Join msdb.dbo.sysjobschedules As jobsched
On sched.schedule_id = jobsched.schedule_id
Where sched.enabled = 1
)
Select job.name As 'jobName'
, sched.scheduleName
, sched.frequency
, sched.subFrequency
, SubString(sched.startTime, 1, 2) + ':'
+ SubString(sched.startTime, 3, 2) + ' - '
+ SubString(sched.endTime, 1, 2) + ':'
+ SubString(sched.endTime, 3, 2)
As 'scheduleTime' -- HH:MM
, SubString(sched.nextRunDate, 1, 4) + '/'
+ SubString(sched.nextRunDate, 5, 2) + '/'
+ SubString(sched.nextRunDate, 7, 2) + ' '
+ SubString(sched.nextRunTime, 1, 2) + ':'
+ SubString(sched.nextRunTime, 3, 2) As 'nextRunDate'
/* Note: the sysjobschedules table refreshes every 20 min,
so nextRunDate may be out of date */
, 'Execute msdb.dbo.sp_update_job #job_id = '''
+ Cast(job.job_id As char(36)) + ''', #enabled = 0;' As 'disableScript'
From msdb.dbo.sysjobs As job
Join myCTE As sched
On job.job_id = sched.job_id
Where job.enabled = 1 -- do not display disabled jobs
Order By nextRunDate;

SQL Server 2000 - last run/execution time of SP/View/UDF

This is a production SQL Server 2000 database with about 1500 database objects (SPs, Views, UDFs). Now, I’m told that about 20% of these database objects are unused by the applications (200 of them mostly small built on multiple platforms/technologies) and I’m tasked to identify them.
Is there a script that I could run against the database to identify the “last run date/time” of these database objects?
Is there any other way to identify the unused database objects – APART FROM browsing through the code? Please note that this is SQL Server 2000. Any help is highly appreciated.
Thank you
I had to write some code for my SQL2000 servers.
I insert these into a table for constant monitoring
This first bit of code will tell you when jobs are scheduled to run
SET #SQL = 'SELECT
J.[name] AS [JobName]
, CASE S.[enabled]
WHEN 1 THEN ''Yes''
WHEN 0 THEN ''No''
END AS [IsEnabled]
, CASE
WHEN [freq_type] = 64 THEN ''Start automatically when SQL Server Agent starts''
WHEN [freq_type] = 128 THEN ''Start whenever the CPUs become idle''
WHEN [freq_type] IN (4,8,16,32) THEN ''Recurring''
WHEN [freq_type] = 1 THEN ''One Time''
END [ScheduleType]
, CASE [freq_type]
WHEN 1 THEN ''One Time''
WHEN 4 THEN ''Daily''
WHEN 8 THEN ''Weekly''
WHEN 16 THEN ''Monthly''
WHEN 32 THEN ''Monthly - Relative to Frequency Interval''
WHEN 64 THEN ''Start automatically when SQL Server Agent starts''
WHEN 128 THEN ''Start whenever the CPUs become idle''
END [Occurrence]
, CASE [freq_type]
WHEN 4 THEN ''Occurs every '' + CAST([freq_interval] AS VARCHAR(3)) + '' day(s)''
WHEN 8 THEN ''Occurs every '' + CAST([freq_recurrence_factor] AS VARCHAR(3))
+ '' week(s) on ''
+ CASE WHEN [freq_interval] & 1 = 1 THEN ''Sunday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 2 = 2 THEN '', Monday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 4 = 4 THEN '', Tuesday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 8 = 8 THEN '', Wednesday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 16 = 16 THEN '', Thursday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 32 = 32 THEN '', Friday'' ELSE '''' END
+ CASE WHEN [freq_interval] & 64 = 64 THEN '', Saturday'' ELSE '''' END
WHEN 16 THEN ''Occurs on Day '' + CAST([freq_interval] AS VARCHAR(3))
+ '' of every ''
+ CAST([freq_recurrence_factor] AS VARCHAR(3)) + '' month(s)''
WHEN 32 THEN ''Occurs on ''
+ CASE [freq_relative_interval]
WHEN 1 THEN ''First''
WHEN 2 THEN ''Second''
WHEN 4 THEN ''Third''
WHEN 8 THEN ''Fourth''
WHEN 16 THEN ''Last''
END
+ '' ''
+ CASE [freq_interval]
WHEN 1 THEN ''Sunday''
WHEN 2 THEN ''Monday''
WHEN 3 THEN ''Tuesday''
WHEN 4 THEN ''Wednesday''
WHEN 5 THEN ''Thursday''
WHEN 6 THEN ''Friday''
WHEN 7 THEN ''Saturday''
WHEN 8 THEN ''Day''
WHEN 9 THEN ''Weekday''
WHEN 10 THEN ''Weekend day''
END
+ '' of every '' + CAST([freq_recurrence_factor] AS VARCHAR(3))
+ '' month(s)''
END AS [Recurrence]
, CASE [freq_subday_type]
WHEN 1 THEN ''Occurs once at ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_start_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
WHEN 4 THEN ''Occurs every ''
+ CAST([freq_subday_interval] AS VARCHAR(3)) + '' Minute(s) between ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_start_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
+ '' & ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_end_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
WHEN 8 THEN ''Occurs every ''
+ CAST([freq_subday_interval] AS VARCHAR(3)) + '' Hour(s) between ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_start_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
+ '' & ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([active_end_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
END [Frequency],
FROM '+ #Server +'.[msdb].[dbo].[sysjobschedules] AS S INNER JOIN
'+ #Server +'.[msdb].[dbo].[sysjobs] AS J ON S.[job_id] = J.[job_id]
WHERE S.[enabled] = 1
ORDER BY J.[Name]'
EXEC (#SQL)
This next bit of code will tell you last run of jobs and if the suceeded or not
SET #SQL = 'SELECT
[sJOB].[job_id] AS [JobID]
,[sJOB].[name] AS [JobName]
,CASE
WHEN [sJOBH].[run_date] IS NULL OR [sJOBH].[run_time] IS NULL THEN NULL
ELSE CAST(
CAST([sJOBH].[run_date] AS CHAR(8))
+ '' ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([sJOBH].[run_time] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
AS DATETIME)
END AS [LastRunDateTime]
, CASE [sJOBH].[run_status]
WHEN 0 THEN ''Failed''
WHEN 1 THEN ''Succeeded''
WHEN 2 THEN ''Retry''
WHEN 3 THEN ''Canceled''
WHEN 4 THEN ''Running''
END AS [LastRunStatus]
, STUFF(
STUFF(RIGHT(''000000'' + CAST([sJOBH].[run_duration] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
AS [LastRunDuration (HH:MM:SS)]
, [sJOBH].[message] AS [LastRunStatusMessage]
, CASE [sJOBSCH].[NextRunDate]
WHEN 0 THEN NULL
ELSE CAST(
CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
+ '' ''
+ STUFF(
STUFF(RIGHT(''000000'' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)), 6)
, 3, 0, '':'')
, 6, 0, '':'')
AS DATETIME)
END AS [NextRunDateTime]
FROM
'+ #Server +'.[msdb].[dbo].[sysjobs] AS [sJOB]
LEFT JOIN (
SELECT
[job_id]
, MAX([next_run_date]) AS [NextRunDate]
, MAX([next_run_time]) AS [NextRunTime]
FROM '+#Server +'.[msdb].[dbo].[sysjobschedules]
GROUP BY [job_id]
) AS [sJOBSCH]
ON [sJOB].[job_id] = [sJOBSCH].[job_id]
LEFT JOIN (
SELECT
[job_id]
, [run_date]
, [run_time]
, [run_status]
, [run_duration]
, [message]
FROM '+ #Server +'.[msdb].[dbo].[sysjobhistory]
WHERE [step_id] = 0
) AS [sJOBH]
ON [sJOB].[job_id] = [sJOBH].[job_id]
-- AND [sJOBH].[RowNumber] = 1
ORDER BY [JobName]'
--PRINT (#SQL)
EXEC (#SQL)
Replace the #Server with your server name or set the variable #Server to the name of the server you want to run the scripts against

SQL Parameter in CASE Statement

Kindly see my Stored Proc below. I'm trying to pass through a value of 1 or 0 from a parameter in a CASE statement.
I get the error which I can tell are in the SELECT statement calling the parameter #payment_status in the CASE statment:
Msg 102, Level 15, State 1, Line 17 Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 21 Incorrect syntax near '='.
Here's the script:
ALTER PROC ash_ap_cash_req_sp (#End_Date NVARCHAR(12),
#Payment_Hold NVARCHAR(32))
AS
SET NOCOUNT ON
DECLARE #debug INT,
#julian_end_date VARCHAR(7),
#ap_cash_req NVARCHAR(4000),
#payment_status VARCHAR(400)
SET #End_Date = RIGHT('00' + CONVERT(VARCHAR(2), datepart(mm, #End_Date)), 2) + '/' + RIGHT('00' + CONVERT(VARCHAR(2), datepart(dd, #End_Date)), 2) + '/' + RIGHT('0000' + CONVERT(VARCHAR(4), datepart(yyyy, #End_Date)), 4)
SET #julian_end_date = (SELECT datediff(dd, '1/1/1753', #End_Date) + 639906)
IF #Payment_Hold = 'All'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag in (0,1)'
END
ELSE IF #Payment_Hold = 'Yes'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag = 1'
END
ELSE IF #Payment_Hold = 'No'
BEGIN
SET #payment_status = '
SELECT payment_hold_flag
FROM dbase.dbo.apvchr
WHERE payment_hold_flag = 0'
END
SET #debug = 0
SET #ap_cash_req = '
IF OBJECT_ID(''temp.dbo.##ash_ap_cash_req_sp'') is NOT NULL
DROP TABLE ##ash_ap_cash_req_sp;
CREATE TABLE ##ash_ap_cash_req_sp
(vendor varchar(12)
, pay_to varchar(12)
, vendor_name varchar(32)
, voucher_no varchar(12)
, invoice_no varchar(32)
, date_doc varchar(12)
--, date_doc_jd varchar(12)
, date_due varchar(12)
--, date_due_jd varchar(12)
, date_applied varchar(12)
--, date_applied_jd varchar(12)
, paid_status varchar(8)
--, payment_status varchar(12)
, payment_hold_status varchar(8)
, amount_open decimal(20,2)
, days_diff float
, days_0_to_30 decimal(20,2)
, days_31_to_60 decimal(20,2)
, days_61_to_90 decimal(20,2)
, days_91_to_120 decimal(20,2)
, days_121_to_150 decimal(20,2)
, total_over_90 decimal(20,2)
, total_over_150 decimal(20,2)
, payment_code varchar(8)
)'
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
SET #ap_cash_req = '
SELECT
m.vendor
, m.pay_to
, m.address_name as vendor_name
, h.trx_ctrl_num as voucher_no
, h.doc_ctrl_num as invoice_no
, CONVERT(varchar(12),dateadd(dd,(h.date_doc- 639906),''1/1/1753''),101) as date_doc
--, h.date_doc as date_doc_jd
, CONVERT(varchar(12),dateadd(dd,(h.date_due- 639906),''1/1/1753''),101) as date_due
--, h.date_due as date_due_jd
, CONVERT(varchar(12),dateadd(dd,(h.date_applied- 639906),''1/1/1753''),101) as date_applied
--, h.date_applied as date_applied_jd
, paid_status = CASE WHEN h.paid_flag = 1
THEN ''Paid''
ELSE ''Not Paid'' END
, h.payment_hold_flag = CASE
WHEN ' + #payment_status + ' = 1 THEN ''On Hold''
ELSE ''Not On Hold''
END as payment_hold_status
, amount_open = (amt_net-amt_paid_to_date)
, h.payment_code
, days_dif = (' + #julian_end_date + ' - h.date_applied)
, days_0_to_30 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-30
THEN h.amt_net --(h.amt_net-h.amt_paid_to_date)
ELSE 0 END
, days_31_to_60 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-60
AND h.date_applied <= ' + #julian_end_date + '-31
THEN h.amt_net
ELSE 0 END
, days_61_to_90 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-90
AND h.date_applied <= ' + #julian_end_date + '-61
THEN h.amt_net
ELSE 0 END
, days_91_to_120 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-120
AND h.date_applied <= ' + #julian_end_date + '-91
THEN h.amt_net
ELSE 0 END
, days_121_to_150 = CASE WHEN h.date_applied >= ' + #julian_end_date + '-150
AND h.date_applied <= ' + #julian_end_date + '-121
THEN h.amt_net
ELSE 0 END
, total_over_90 = CASE WHEN h.date_applied <= ' + #julian_end_date + '-91
THEN h.amt_net
ELSE 0 END
, total_over_150 = CASE WHEN h.date_applied <= ' + #julian_end_date + '-151
THEN h.amt_net
ELSE 0 END
FROM dbase.dbo.apvchr h
JOIN dbase.dbo.apvdet d
ON h.trx_ctrl_num = d.trx_ctrl_num
JOIN dbase.dbo.master m
ON h.vendor = m.vendor
AND h.pay_to = m.pay_to
GROUP BY m.vendor, m.pay_to, m.address_name
, h.trx_ctrl_num, h.doc_ctrl_num, h.date_doc, h.date_due, h.date_applied, h.paid_flag, h.payment_hold_flag
, h.amt_net, h.amt_paid_to_date, h.payment_code, h.payment_hold_flag
--ORDER BY NEWID()
'
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
SET #ap_cash_req = '
SELECT * FROM ##ash_ap_cash_req_sp
';
SET #ap_cash_req = '
DROP TABLE ##ash_ap_cash_req_sp
';
IF #debug = 1
BEGIN
PRINT #ap_cash_req
PRINT ''
END
ELSE
BEGIN
EXEC sp_executesql #ap_cash_req
END
EXEC dbase.dbo.ash_ap_cash_req_sp;1 '03/11/2013','Yes'
Because #payment_status is a 'SELECT...', you'll need to wrap it with braces
h.payment_hold_flag = CASE
WHEN ('+#payment_status+') = 1 THEN ''On Hold''
ELSE ''Not On Hold''
END as payment_hold_status
but, that aside, I would question the syntax :
, amount_open = (amt_net-amt_paid_to_date)
- do you mean
, (amt_net-amt_paid_to_date) as amount_open?

How SQL calculates NEXT_RUN_DATE for a job schedule?

I have to make a manual calculation of the next run date for a job, can you help me?
to get the next run date for a job you can use then sysschedules and sysjobschedules tables
check the next_run_date and next_runtime columns from the table sysjobschedules
next_run_date int Next date on which
the job is scheduled to run. The date
is formatted YYYYMMDD.
next_run_time int Time at which the
job is scheduled to run. The time is
formatted HHMMSS, and uses a 24-hour
clock.
see this script
Select sched.*,jobsched.* FROM msdb.dbo.sysschedules AS sched
inner Join msdb.dbo.sysjobschedules AS jobsched ON sched.schedule_id = jobsched.schedule_id
or you can use the msdb.dbo.sp_help_jobschedule stored procedure, to get the same info.
UPDATE
if you need calculate manually the next_run_date you must check the sysschedules table and see the freq_interval, freq_subday_type, freq_subday_interval, freq_relative_interval, freq_recurrence_factor, active_start_date, active_start_time columns to determine the formula.
check this link to see an example of use.
Check this one:
SELECT
J.NAME JOB,
DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112))))
JOB_STARTED,
DATEADD(SS,((H.RUN_DURATION)%10000)%100,DATEADD(N,((H.RUN_DURATION)%10000)/100,DATEADD(HH,(H.RUN_DURATION)/10000,DATEADD(SS,(H.RUN_TIME)%100,DATEADD(N,(H.RUN_TIME/100)%100,DATEADD(HH,H.RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),H.RUN_DATE),112)))))))
JOB_COMPLETED,
CONVERT(VARCHAR(2),(H.RUN_DURATION)/10000) + ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)/100)+ ':' +
CONVERT(VARCHAR(2),((H.RUN_DURATION)%10000)%100) RUN_DURATION,
CASE H.RUN_STATUS
WHEN 0 THEN 'FAILED'
WHEN 1 THEN 'SUCCEEDED'
WHEN 2 THEN 'RETRY'
WHEN 3 THEN 'CANCELED'
WHEN 4 THEN 'IN PROGRESS'
END RUN_STATUS
,CASE S.FREQ_TYPE
WHEN 1 THEN 'ONCE'
WHEN 4 THEN ' DAILY'
WHEN 8 THEN ' WEEKLY'
WHEN 16 THEN ' MONTHLY'
WHEN 32 THEN ' MONTHLY RELATIVE'
WHEN 64 THEN ' WHEN SQL SERVER'
ELSE 'N/A' END [FREQ]
,CASE
WHEN S.NEXT_RUN_DATE > 0 THEN DATEADD(N,(NEXT_RUN_TIME%10000)/100,DATEADD(HH,NEXT_RUN_TIME/10000,CONVERT(DATETIME,CONVERT(VARCHAR(8),NEXT_RUN_DATE),112)))
ELSE CONVERT(DATETIME,CONVERT(VARCHAR(8),'19000101'),112) END NEXT_RUN
FROM
MSDB..SYSJOBHISTORY H,
MSDB..SYSJOBS J,
MSDB..SYSJOBSCHEDULES S,
(
SELECT
MAX(INSTANCE_ID) INSTANCE_ID
,JOB_ID
FROM MSDB..SYSJOBHISTORY GROUP BY JOB_ID
) M
WHERE
H.JOB_ID = J.JOB_ID
AND
J.JOB_ID = S.JOB_ID
AND
H.JOB_ID = M.JOB_ID
AND
H.INSTANCE_ID = M.INSTANCE_ID
-- IF you want to check all job for today then uncomments below
-- AND
-- RUN_DATE = (YEAR(GETDATE())*10000) + (MONTH(GETDATE()) * 100) + DAY(GETDATE())
ORDER BY NEXT_RUN
The short answer is that there's no single formula - it varies by value of freq_type.
The site seems to be down at the moment of writing, but there is an article at http://www.sqlmag.com/Article/ArticleID/99593/sql_server_99593.html which covers how to derive this information. Unfortunately, the site doesn't allow Google to cache its content, so it can't be retrieved until the site comes back up
This looks like a decent alternative source for the kind of query you're trying to write.
here is a very nice script where you can get the next run date.
-- http://www.sqlprofessionals.com/blog/sql-scripts/2014/10/06/insight-into-sql-agent-job-schedules/
SELECT [JobName] = [jobs].[name]
,[Enabled] = CASE [jobs].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Scheduled] = CASE [schedule].[enabled] WHEN 1 THEN 'Yes' ELSE 'No' END
,[Next_Run_Date] =
CASE [jobschedule].[next_run_date]
WHEN 0 THEN CONVERT(DATETIME, '1900/1/1')
ELSE CONVERT(DATETIME, CONVERT(CHAR(8), [jobschedule].[next_run_date], 112) + ' ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [jobschedule].[next_run_time]), 6), 5, 0, ':'), 3, 0, ':'))
END
,[Category] = [categories].[name]
,[Owner] = SUSER_SNAME([jobs].[owner_sid])
,[Description] = [jobs].[description]
,[Occurs] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'Once'
WHEN 4 THEN 'Daily'
WHEN 8 THEN 'Weekly'
WHEN 16 THEN 'Monthly'
WHEN 32 THEN 'Monthly relative'
WHEN 64 THEN 'When SQL Server Agent starts'
WHEN 128 THEN 'Start whenever the CPU(s) become idle'
ELSE ''
END
,[Occurs_detail] =
CASE [schedule].[freq_type]
WHEN 1 THEN 'O'
WHEN 4 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' day(s)'
WHEN 8 THEN 'Every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' weeks(s) on ' +
LEFT(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END ,
LEN(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN 'Sunday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN 'Monday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN 'Tuesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN 'Wednesday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN 'Thursday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN 'Friday, ' ELSE '' END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN 'Saturday, ' ELSE '' END
) - 1
)
WHEN 16 THEN 'Day ' + CONVERT(VARCHAR, [schedule].[freq_interval]) + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
WHEN 32 THEN 'The ' +
CASE [schedule].[freq_relative_interval]
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 4 THEN 'Third'
WHEN 8 THEN 'Fourth'
WHEN 16 THEN 'Last'
END +
CASE [schedule].[freq_interval]
WHEN 1 THEN ' Sunday'
WHEN 2 THEN ' Monday'
WHEN 3 THEN ' Tuesday'
WHEN 4 THEN ' Wednesday'
WHEN 5 THEN ' Thursday'
WHEN 6 THEN ' Friday'
WHEN 7 THEN ' Saturday'
WHEN 8 THEN ' Day'
WHEN 9 THEN ' Weekday'
WHEN 10 THEN ' Weekend Day'
END + ' of every ' + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ' month(s)'
ELSE ''
END
,[Frequency] =
CASE [schedule].[freq_subday_type]
WHEN 1 THEN 'Occurs once at ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 2 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Seconds(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 4 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Minute(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
WHEN 8 THEN 'Occurs every ' +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ' Hour(s) between ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ':'), 3, 0, ':') + ' and ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ':'), 3, 0, ':')
ELSE ''
END
,[AvgDurationInSec] = CONVERT(DECIMAL(10, 2), [jobhistory].[AvgDuration])
FROM [msdb].[dbo].[sysjobs] AS [jobs] WITh(NOLOCK)
LEFT OUTER JOIN [msdb].[dbo].[sysjobschedules] AS [jobschedule] WITh(NOLOCK)
ON [jobs].[job_id] = [jobschedule].[job_id]
LEFT OUTER JOIN [msdb].[dbo].[sysschedules] AS [schedule] WITh(NOLOCK)
ON [jobschedule].[schedule_id] = [schedule].[schedule_id]
INNER JOIN [msdb].[dbo].[syscategories] [categories] WITh(NOLOCK)
ON [jobs].[category_id] = [categories].[category_id]
LEFT OUTER JOIN
( SELECT [job_id], [AvgDuration] = (SUM((([run_duration] / 10000 * 3600) +
(([run_duration] % 10000) / 100 * 60) +
([run_duration] % 10000) % 100)) * 1.0) / COUNT([job_id])
FROM [msdb].[dbo].[sysjobhistory] WITh(NOLOCK)
WHERE [step_id] = 0
GROUP BY [job_id]
) AS [jobhistory]
ON [jobhistory].[job_id] = [jobs].[job_id];