View (and Disable) SQL Agent Jobs with TSQL
Recently, I wanted to find a list of all SQL Agent Jobs running on various servers. I was able to view this in SSMS, of course, but I wanted to be able to copy/paste and toss this into a spreadsheet. So instead of using SSMS, I wrote the script below, with significant help from the sysschedules entry in BOL, to show me the same information, using T-SQL. I also include a script to disable the job, because that's just how I roll.
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;
Not sure what I'm doing with the @weekDay table? Then check out my post on bitwise operations in T-SQL.
Happy Coding!
Michelle Ufford (aka SQLFool)
PS: I haven't tested this with every possible setting, just the ones I use. If I missed something, please let me know so I can correct it.
PPS: the sysjobschedules table only refreshes every 20 min, so the nextRunDate value may be a little out of date.
Source: http://sqlfool.com/2009/02/view-sql-agent-jobs-tsql/
T-SQL Bitwise Operations
I've seen bit-product columns from time-to-time, mostly in SQL Server 2000 system tables, but it's never been something I've had to work with. And when I've needed to, I've known how to figure out which options are selected, i.e. a bit product of 9 means options 8 and 1 are selected. If you've ever taken a look at the [status] column on the sysdatabases table (SQL 2000), you'll know what I'm talking about.
What I've never known how to do, until recently, was calculate these options programmatically. That's why, when I noticed the [freq_interval] on the sysschedules table was a bit-product column, I decided to spend a little time figuring it out. Fortunately for me, a couple of my awesome co-workers, Jeff M. and Jason H., have worked with this before and were able to explain it to me. And, it turns out, it's actually quite easy.
Let me back up a few steps in case you're not familiar with this topic. If you check out the Books Online entry for the sysschedules table (2005), you'll notice the following statement:
freq_interval is one or more of the following:
1 = Sunday
2 = Monday
4 = Tuesday
8 = Wednesday
16 = Thursday
32 = Friday
64 = Saturday
When I looked at the actual value in the table, the schedule has a [freq_interval] value of 42, which is the sum of the bit values for the days selected.
If there were more than 7 options, the bit values would continue to double, i.e. 128, 256, etc. And regardless of how many bit values you select, you're guaranteed one and only one possible answer, as the sum of all previous bit values will never exceed the next bit value:
1 + 2 = 3
1 + 2 + 4 = 7
1 + 2 + 4 + 8 = 15
Knowing this, I'm able to retrieve the values manually: I start with the highest bit value that does not exceed 42, then subtract it; I repeat until I'm left with 0.
So...
42 - 32 = 10
10 - 8 = 2
2 - 2 = 0
That means my job is scheduled to run on Friday's (32), Wednesday's (8), and Monday's (2).
Now how do I do this with T-SQL? SQL Server provides an operator specifically for this task: the bitwise AND operator (&). For now, I'm going to skip the "why" behind this and just get to the practical application. If you're interested in the "why," let me know and I'll write a follow-up post on binary and logical AND and OR operations.
For example, to use the bitwise AND to find out which days are selected...
SELECT 42 & 1 AS 'Sunday' , 42 & 2 AS 'Monday' , 42 & 4 AS 'Tuesday' , 42 & 8 AS 'Wednesday' , 42 & 16 AS 'Thursday' , 42 & 32 AS 'Friday' , 42 & 64 AS 'Saturday';
... will return ...
Sunday Monday Tuesday Wednesday Thursday Friday Saturday ----------- ----------- ----------- ----------- ----------- ----------- ----------- 0 2 0 8 0 32 0
If the result is not equal to zero, then that day is selected. Easy as key lime pie, right?
Now let's take it a step further and create our own working example. Let's say we're going to track the characteristics of various objects in a single bit-product column (note: this is not necessarily the best way to accomplish this in the real world, but it's a good illustration). First, set up a table to use in our example. This table will have a column, [attributes], which will hold the sum of our bit values.
CREATE TABLE myTable ( id INT IDENTITY(1,1) , item VARCHAR(10) , attributes INT ); INSERT INTO myTable SELECT 'Broccoli', 200 UNION All SELECT 'Tomato', 193 UNION All SELECT 'Car', 276 UNION All SELECT 'Ball', 292;
Next, we're going to create a table variable that holds characteristics and their values. We'll then join these two tables together to see which attributes exist for each item.
DECLARE @statusLookup TABLE ( attribute INT , VALUE VARCHAR(10) ); INSERT INTO @statusLookup SELECT 1, 'Red' UNION All SELECT 4, 'Blue' UNION All SELECT 8, 'Green' UNION All SELECT 16, 'Metal' UNION All SELECT 32, 'Plastic' UNION All SELECT 64, 'Plant' UNION All SELECT 128, 'Edible' UNION All SELECT 256, 'Non-Edible'; SELECT a.item, b.VALUE FROM myTable a Cross Join @statusLookup b WHERE a.attributes & b.attribute <> 0 ORDER BY a.item , b.VALUE
You should get this result:
item value ---------- ---------- Ball Blue Ball Non-Edible Ball Plastic Broccoli Edible Broccoli Green Broccoli Plant Car Blue Car Metal Car Non-Edible Tomato Edible Tomato Plant Tomato Red
Great, now we know broccoli is edible! Let's apply a little XML to clean up the results...
SELECT a.item , REPLACE( REPLACE( REPLACE(( SELECT VALUE FROM @statusLookup AS b WHERE a.attributes & b.attribute <> 0 ORDER BY b.VALUE FOR XML Raw) , '"/><row value="', ', '), '<row value="', ''), '"/>', '') AS 'attributes' FROM myTable a ORDER BY a.item;
item attributes ---------------------------------------- Ball Blue, Non-Edible, Plastic Broccoli Edible, Green, Plant Car Blue, Metal, Non-Edible Tomato Edible, Plant, Red
Voila! There you have it, how to use the bitwise AND (&) operator to retrieve multiple values from a bit-product column. Pretty neat stuff!
Special thanks to Jeff M. and Jason H. for their assistance.
Happy Coding!
Michelle Ufford (aka SQLFool)
Source: http://sqlfool.com/2009/02/bitwise-operations/
Categories
- Business Intelligence
- Internals
- Miscellaneous
- PASS
- Performance & Tuning
- Presentations
- SQL 2008
- SQL Tips
- Syndication
- T-SQL Scripts
Subscribe to my blog!
| Like what you see? Subscribe! |
![]() |
Around the Web
Recent Tweets
- @zippy1981 I'm actually using @RedGate SQL Compare right now. It's worth every penny. #sqlhelp #redgate
- +1 :) RT @onpnt: Very well said, Janice :) @JaniceCLee your blog if full of WIN http://bit.ly/aZ4wPR
- @SQLDBA You're flying out of Orlando so there's def the possibility of a better deal. But I wouldn't do it unless you're a morning person :)


