How to query currently running SQL Server Agent jobs

By Feodor, March 9, 2010

Today I went on a quest to discover a way to list all currently running SQL Server Agent jobs. As every other quest, this one also started with Google-ing. :)

Within 2 minutes I found this great post by Brent Ozar on SQLServerPedia. Why is this post so great? It is so great because Brent figured that if you query only the sysjobs and the sysjobhistory tables you will not get accurate current job status. I.e. in the sysjobhistory table you have a column run_status, however (even though according to the BOL the possible values for this column are “Status of the job execution: 0 = Failed,1 = Succeeded,2 = Retry,3 = Canceled,4 = In progress”) in reality, the value will never be 4 (In Progress). Actually, in the  sysjobhistory table is kept historical data of each job step executed, which means that the status of the step is updated only after the next step is executed. In other words, the table is NOT updated in real time, nor every other second.

So, Brent figured out that there is a undocumented stored procedure sys.xp_sqlagent_enum_jobs, which is part of sp_help_job, which can give the current execution status of the Agent Job.

Even though I found a way to get the currently running jobs, I was not happy with this script because it runs only on SQL 2005 / 2008.

What should I do if I have a SQL 2000 instance and am very curious about the currently running jobs?

With a bit of Tim Chapman’s help (the master of www.SQLServerNation.com) I figured out how to do it. THANK YOU, Tim!

Here is the final script, which will run on SQL 2000, 2005 and 2008, and which will give you the currently running SQL Server agent jobs. (As you can see, the difference with Brent’s script is very little: instead of “sys.xp_sqlagent_enum_jobs” I am using “master.dbo.xp_sqlagent_enum_jobs” and I am limiting the resultset to get only the currently running jobs by using “where x.running = 1″).

Simple as it is. Enjoy.

IF EXISTS (SELECT *

           FROM    tempdb.dbo.sysobjects

           WHERE   id = OBJECT_ID(N'[tempdb].[dbo].[Temp1]')

                )

        DROP TABLE [tempdb].[dbo].[Temp1]

GO

CREATE TABLE [tempdb].[dbo].[Temp1]

(

         job_id uniqueidentifier NOT NULL,

         last_run_date nvarchar (20) NOT NULL,

         last_run_time nvarchar (20) NOT NULL,

         next_run_date nvarchar (20) NOT NULL,

         next_run_time nvarchar (20) NOT NULL,

         next_run_schedule_id INT NOT NULL,

         requested_to_run INT NOT NULL,

         request_source INT NOT NULL,

         request_source_id sysname

                   COLLATE database_default NULL,

         running INT NOT NULL,

         current_step INT NOT NULL,

         current_retry_attempt INT NOT NULL,

         job_state INT NOT NULL)

DECLARE @job_owner   sysname

DECLARE @is_sysadmin   INT

SET @is_sysadmin   = isnull (is_srvrolemember ('sysadmin'), 0)

SET @job_owner   = suser_sname ()

INSERT INTO [tempdb].[dbo].[Temp1]

   --EXECUTE sys.xp_sqlagent_enum_jobs @is_sysadmin, @job_owner

   EXECUTE master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @job_owner

UPDATE [tempdb].[dbo].[Temp1]

   SET last_run_time    = right ('000000' + last_run_time, 6),

       next_run_time    = right ('000000' + next_run_time, 6);

       -----

         SELECT j.name AS JobName,

       j.enabled AS Enabled,

       CASE x.running

          WHEN 1

          THEN

             'Running'

          ELSE

             CASE h.run_status

                WHEN 2 THEN 'Inactive'

                WHEN 4 THEN 'Inactive'

                ELSE 'Completed'

             END

       END

          AS CurrentStatus,

       coalesce (x.current_step, 0) AS CurrentStepNbr,

       CASE

          WHEN x.last_run_date > 0

          THEN

             convert (datetime,

                        substring (x.last_run_date, 1, 4)

                      + '-'

                      + substring (x.last_run_date, 5, 2)

                      + '-'

                      + substring (x.last_run_date, 7, 2)

                      + ' '

                      + substring (x.last_run_time, 1, 2)

                      + ':'

                      + substring (x.last_run_time, 3, 2)

                      + ':'

                      + substring (x.last_run_time, 5, 2)

                      + '.000',

                      121

             )

          ELSE

             NULL

       END

          AS LastRunTime,

       CASE h.run_status

          WHEN 0 THEN 'Fail'

          WHEN 1 THEN 'Success'

          WHEN 2 THEN 'Retry'

          WHEN 3 THEN 'Cancel'

          WHEN 4 THEN 'In progress'

       END

          AS LastRunOutcome,

       CASE

          WHEN h.run_duration > 0

          THEN

               (h.run_duration / 1000000) * (3600 * 24)

             + (h.run_duration / 10000 % 100) * 3600

             + (h.run_duration / 100 % 100) * 60

             + (h.run_duration % 100)

          ELSE

             NULL

       END

          AS LastRunDuration

  FROM          [tempdb].[dbo].[Temp1] x

             LEFT JOIN

                msdb.dbo.sysjobs j

             ON x.job_id = j.job_id

          LEFT OUTER JOIN

             msdb.dbo.syscategories c

          ON j.category_id = c.category_id

       LEFT OUTER JOIN

          msdb.dbo.sysjobhistory h

       ON     x.job_id = h.job_id

          AND x.last_run_date = h.run_date

          AND x.last_run_time = h.run_time

          AND h.step_id = 0

            where x.running = 1
  • Share/Bookmark

Resource Database in SQL Server

By Feodor, January 31, 2010

In SQL Server 2005 a new method of handling system objects was introduced. The Resource database is a hidden system databse which is unique per each instance of SQL Server 2005 / 2008. This database contains all system objects. Logically these objects appear in the sys. schema of each database. The Resource Database does not contain any user data or metadata. The filenames for the Resource Database are called mssqlsystemresource.mdf and mssqlsystemresource.ldf.

In SQL 2005 the database is located in <drive>:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\ folder. During the installation, the database will be in the same folder as the master database.

In SQL 2008 the Resource Database is located in <drive>: \Program Files\Microsoft SQL Server\MSSQL10.<instance_name>\MSSQL\Binn folder. Note that in SQL 2008 it is not mandatory to keep the master database in the same location as the Resource Database.

In a clustered environment, the Resource Database is located in the \Data folder on a shared disk drive. The ID for the Resource Database will be always 32767.

Benefits of the Resource Database structure:

  • before SQL 2005 the only way to undo the applied changes during a service pack installation was to re-install the instance and apply all the service packs / hotfixes up until that point.
  • in SQL 2005 / 2008 it is much easier to replicate or undo changes made by the hotfix / SP update, since the changes are made only to the Resource Database, which in its turn affect the objects on the sys. schema of the particular instance.
  • If hotfix / SP changes need to be introduced to multiple instances, the DBA needs to copy over the upgraded mssqlsystemresource.mdf and mssqlsystemresource.ldf files.
  • If the changes need to be r,olled back, the DBA needs to copy back the previous versions of the mssqlsystemresource.mdf and mssqlsystemresource.ldf files.

To query the version of the Resource Database, execute the following code:


SELECT SERVERPROPERTY('ResourceVersion')
GO
SELECT SERVERPROPERTY('ResourceLastUpdateDateTime');
GO

How to backup the Resource Database: you may not backup the database from SSMS or by using T-SQL. You can backup the database by copying the physical files of the database. You can copy the files even if the SQL Server instance is running. (you are not able to copy any other database files while the SQL Server instance is running.)

How to restore the Resource Database: you may not restore the database from SSMS or by using T-SQL. The DBA has to manually copy the files in the respective folders. In a disaster recovery situation, the Resource Database has to be copied to the appropriate location prior to restoring of the master database. Otherwise, the DBA will have to apply all changes by hotfixes / SP before you can bring up the instance as it was prior to the disaster.

Disaster recovery planning: Make sure to include the Resource Database backups in your disaster recovery planning.

  • Share/Bookmark

MCP!

By Feodor, February 8, 2010

After some serious studying I passed my first Microsoft MCP certification.

What I have learned is:
1. that I have much more to learn
2. that the Microsoft Press books are one of the best ones for preparation
3. the exam is not too hard, but one must ‘read between the lines’ in order to get the correct answer.

What is next:
1. BI certification
2. SQL Server Developer certification
3. Master program.

I would like to thank the following people:
1. my wife, who is supportive and patient with all my SQL Server experiments in the living room :)
2. my boss, who has taught me plenty
3. Brent Ozar, for the enlightening articles on his site

  • Share/Bookmark

SQL Search tool

By Feodor, February 9, 2010

Here is a great tool by RedGate which allows the DBA to search throughout all objects in a database. The tool is integrated with SSMS, and it works for both SQL 2005 and SQL 2008.

Here are some benefits:

  • you can easily find all references to an object in your database
  • you can look up any object and “jump to it”
  • you can search even for whole or fragments of words …

You can view more detail and download from this site.

  • Share/Bookmark

Save the day: DAC

By Feodor, February 9, 2010

If all goes “nuts and bolts” with your SQL Server – what do you do?

Well, hopefully you have heard about the DAC before. If not, you hear about it now. DAC is the Dedicated admin connection for SQL Server. As an admin you should make sure that the DAC is enabled, tested and that you have a set of scripts which will give you quick information about your system, once you are connected.

DAC is like a back door. If any other connections to your server are refused for one reason or another, you will still be able to connect through the DAC and run some queries to determine the problem, and eventually kill a process etc…

So, how do we enable DAC?

In SQL 2005 you can go to the “Surface Area Configuration”(SAC) and then SAC for Features. From there you can enable the DAC.

In SQL 2008 you can right-click the instance in SSMS and go to Facets, select the Surface Area Configuration and change the “RemoteDacEnabled” value to True.

Or, you could run the following script:

Use master
GO
sp_configure 'show advanced options' , 1
GO
/* 0 = Allow Local Connection, 1 = Allow Remote Connections*/
sp_configure 'remote admin connections', 1
GO
RECONFIGURE
GO

And then, you can connect to SQL Server by typing the ADMIN: word before the server/instance name (for example: ADMIN:MySQLServerName or ADMIN:MySQLServerName\MyInstance).

If you keep getting the following error “Dedicated administrator connections are not supported.”, then you should keep in mind that you can connect to the DAC ONLY through a Query Window, and NOT through a Database Engine Query (when it comes to using SSMS for the DAC). Otherwise you can connect through a command line, of course. :)

When it comes to a small set of queries you should have ready…

-- Locking Information

SELECT * FROM sys.dm_tran_locks

GO

-- Cache Status

SELECT * FROM sys.dm_os_memory_cache_counters

GO

-- Active Sessions

SELECT * FROM sys.dm_exec_sessions

GO

-- Requests Status

SELECT * FROM sys.dm_exec_requests

GO

Use master
GO
sp_configure ’show advanced options’ , 1
GO
/* 0 = Allow Local Connection, 1 = Allow Remote Connections*/
sp_configure ‘remote admin connections’, 1
GO
RECONFIGURE
GO
  • Share/Bookmark

SQL Server 2008 R2 blocked on install by Express tools

By Feodor, February 11, 2010

I was trying to install a named instance of SQL Server 2008 R2 on my machine, and I got an error telling me that the installation cannot continue because the SQL 2005 Express tools are installed. I had never installed SQL 2005 on my machine, and after some searching I found that the error is due to the following entry in the registry:

SOFTWARE\Microsoft\Microsoft SQL Server\90\Tools\ShellSEM

Well, it turned out that this key had something to do with me installing some RedGate software on my machine previously.

Here is how you fix it: Backup the registry key, delete it, continue with the SQL Server install, restore the registry key.

  • Share/Bookmark

How to compress your database… REALLY!

By Feodor, February 17, 2010

NB: Do NOT try any idea in this post at home, and DO NOT try it on your production server!

Here are some thoughts on database backup strategies, which were brought upon after reading Brent Ozar’s post on the topic.

In short, the problem is that Brent has a database which has to be backed up and the backup file needs to be as small as possible in order to save money from the file transfer to / from the colo facility. (They charge by the byte. )

So, the proposed solution is:

  1. Restore the production backups
  2. Do some work on them to decrease their size
  3. Back up the smaller databases

The “Do some work” part is:

  1. Script out all of the non-clustered indexes in the database
  2. Save those definitions to a table (or a stored procedure)
  3. Create a stored proc that will loop through those index definitions and recreate them later
  4. Drop the indexes

Also, Brent suggests to rebuild all tables with 100% fill factor.

Now. Sounds great, but only if you have non-clustered indexes and fill factors less than 100. And if you don’t? Here are some thoughts on this:

1. How about starting with a flawless database design? Following the design best practices can really give you good performance and save you quite a few bytes: use proper data types and proper normalization.

2. How about some backup strategy which includes differential backups, partition backups, and so on? You don’t really need to backup archived (and rarely or never changing) data too often.

3. How about using sparse columns, if possible.

And after this, it all “flies off the handle”: :)

4. How about exporting all data to raw or flat files, compressing it with zip, rar or something, then backing up the database and transferring it?

5. How about finding a cheaper colo center? Some that does not charge by the byte?

6. How about not backing up anything? Who needs backups, after all.

Note: with this blog post I do NOT mean to challenge anyone (especially Brent, whom I respect endlessly as a SQL Server professional!), and I hope I am not offending anyone. The reason I am writing this note is the fact that I have seen so many poor database designs, so many misused datatypes and so many databases that have never been backed up, that when I read Brent’s post, I thought “Ha, it must take a data transfer paid by the byte to make people think how to optimize the space used by their data!”

And finally, here is a really good post, which came also as an answer to Brent’s blog: Chad Miller explains how to use PowerShell to back up all non-clustered indexes in a database.

  • Share/Bookmark

How to disable parallelism on your SQL Server

By Feodor, March 10, 2010

Very often parallelism can cause performance degradation in OLTP systems. In order to disable it, execute the following query:


USE master
EXEC sp_configure 'show advanced option', '1'
go
reconfigure
go

exec sp_configure 'max degree of parallelism', 1
go
reconfigure
go
  • Share/Bookmark

Who is running queries on your SQL Server?

By Feodor, March 10, 2010

Here is a query which will run on SQL 2000 and will tell you who is executing what queries on the server in this moment.


CREATE TABLE #sp_who2
(
SPID INT,
Status VARCHAR(1000) NULL,
Login SYSNAME NULL,
HostName SYSNAME NULL,
BlkBy SYSNAME NULL,
DBName SYSNAME NULL,
Command VARCHAR(1000) NULL,
CPUTime INT NULL,
DiskIO INT NULL,
LastBatch VARCHAR(1000) NULL,
ProgramName VARCHAR(1000) NULL,
SPID2 INT
)

Create Table #SqlStatement
(spid int,
statement varchar(8000))
create table #temp (x varchar(100), y int, s varchar(1000), id int
identity (1,1))

INSERT #sp_who2 EXEC sp_who2

Declare @spid varchar(10)
Declare @Statement varchar(8000)
declare @sql varchar(1000)
DECLARE SpidCursor Cursor
FOR Select spid from #sp_who2
OPEN SpidCursor
FETCH NEXT FROM SpidCursor
INTO @spid
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'dbcc inputbuffer (' + @spid + ')'
insert #temp
exec (@sql)
Insert Into #SqlStatement
Select @spid, s From #Temp where id = (Select max(id) from #Temp)
FETCH NEXT FROM SpidCursor
INTO @spid
END
Close SpidCursor
Deallocate SpidCursor

Select B.Statement, A.* from #sp_who2 A Left JOIN
#SqlStatement B ON A.spid = B.spid

Drop Table #Temp
Drop Table #SqlStatement
Drop Table #sp_who2
  • Share/Bookmark

Get the top CPU consumer in SQL Server 2000

By Feodor, March 10, 2010

Here is a good script which will give you the current (in the last minute) top CPU consumers for your SQL Server 2000.


use master

go

Select d.name as 'DatabaseName',  spid, p.status, cmd,
p.loginame, nt_username, hostname, program_name,
cpu, physical_io, memusage, blocked
into ##FirstLook
from sysprocesses p (nolock)
join sysdatabases d (nolock)
on p.dbid = d.dbid
order by D.name, nt_username

waitfor delay '00:01:00'

Select d.name as 'DatabaseName', spid, p.status, cmd,
p.loginame, nt_username, hostname, program_name,
cpu, physical_io, memusage, blocked
into ##SecondLook
from sysprocesses p (nolock)
join sysdatabases d (nolock)
on p.dbid = d.dbid
order by D.name, nt_username

Select b.DatabaseName, b.spid, b.status, b.loginame,
b.nt_UserName, b.hostName, b.Program_name, b.spid,
B.cpu - isnull(A.cpu,0) as MinuteCPU,
b.cpu as TotCPU,
b.Physical_io - isnull(a.physical_io,0) as MinuteIO,
b.physical_IO as totIO,
b.memusage - isnull(a.memusage,0) as MinuteMem,
b.memusage as TotMem, b.blocked as BlkBy
from ##firstLook a
right outer join ##secondLook b
on a.spid = b.spid
and a.databasename = b.databaseName
and a.loginame = b.loginame
order by 9 desc,11 desc,13 desc

--select * from ##firstLook
--select * from ##secondLook

drop table ##firstLook
drop table ##SecondLook
  • Share/Bookmark

How to get stuck in a field of snow

By sibir1us, March 6, 2010
  1. Find a field of snow.
  2. Jump in the snow.
  3. Try to get out of the snow.
  • Share/Bookmark

Sigtuna – early spring

By sibir1us, March 6, 2010
  • Share/Bookmark

Lake Vättern, Sweden is Brilliantly beautiful

By sibir1us, March 6, 2010

A trip to the southern Sweden proved to me (once again!) that the nature in the country is so magnificent, the quality of light is breathtaking and the air is crystal-clear at a temperature of -10 C. Here are some pictures from Lake Vättern.

  • Share/Bookmark

How to destroy the work environment

By sibir1us, March 1, 2010

Some thoughts on work ethics and productivity have been buzzing in my head for a while now.I have read one too many advices on how to improve the work ethics and how to give better results, and I have seen one too many managers fail in their attempts to organize the day. Hence, I would like to write about the sure ways to give poor results at work and how to accomplish very little.

So here is how the reality might be. You can really spend day after day surviving a hurricane of meetings, briefings, forwarded emails, action lists… and still not make a single change. The mentality of the average employee is agreeing with a statement like this “I just work here… (For one or other reason) I am not hired to make a change, but to be in peace with the others and to get paid.” And yes, this is the easier way to go about it. (I mean: life happens too fast anyway – imagine if all those average employees all of a sudden would get involved and all try to make a change! The human race would evolve beyond all frontiers!)

As a kid I spent a lot of time with my grandma, who was constantly working in the garden, growing fruits and vegetables. Sometimes she would ask me for some help, she would interrupt my play, and of course as a response I would perform what I was asked slowly and without being eager to be done with the job soon (of course the occasional “unintentional” spill would take place).  After a while my grandma would say “Well, either do it right, or don’t do it at all!”. With these words she would send me back to my games.

Nowadays, it is different. But not really. In corporations and in medium businesses there are departments, structures and work descriptions that are vague, or even barely defined.

Enough of this. Here is a list of things you should do in order to be average, blend in and not to improve:

  1. Never assume responsibility. Leave things as they are.If it gets really bad, though, you can always delegate to other team members.
  2. Never say what you think – if you think something is wrong, do not mention it, because it might create more work for you or for your colleagues. Even worse – maybe the management will have to re-think the organizational strategy (and who knows where this will go!).
  3. If you see a colleague doing nothing or watching youtube, for example, do not say anything, but instead open your own browser, navigate to youtube and play something good and soothing.
  4. Get yourself under a negligent manager. Actually, if you can even get under a incompetent manager – that’s even better. Why? Because a negligent / incompetent manager will not ask questions, and will stay off sight.
  5. Talk a lot, but say nothing. Talking is known to trigger some center of the brain of the listeners, which in its turn makes them believe that you are knowledgeable and good at what you do.But try to stay on general subjects, and stay away from discussing details. There is a big difference between “what” and “how”. Stick to the “what” part, and do not cross the line to the “how”.
  6. Don’t do much. Don’t even show that you are capable of doing extra things. Usually when your colleagues / managers see that you like to take initiative, they might actually take advantage of you, and before you know it, you will be expected to do it. And soon after that, if you don’t take the initiative, your colleagues / managers will be disappointed.
  7. Participate in all company meetings – drink, smoke, joke and so on. You actually draw less attention when you participate in the “games” then when you don’t.
  8. Open as many web browsers / applications as your PC can handle. This makes the others believe that you are working hard.
  9. Do not talk unless you really have to. Just point in different directions, as long as you can.
  10. Do not surprise people. Usually surprises are not welcome in the team. Do not improve – stay as calm as possible and don’t give even a sign if you are bothered by something.

As a grand finale I would like to tell a story (a true story, I assure you!). It was some years ago in the US, when I was applying for a new job at a medium company. I showed up for the interview, the first part of the interview consisted of plenty of technical questions, and when it was over, the interviewer said to me “Great, now I will introduce one of the team members, and potential future colleague of yours. Talk to them and ask them about the team, about the position etc.”. So, here is the team member sitting across the table, and here is me wondering what to ask. The first question that comes to my mind is “What do you like best about your position? What do you expect?” And the answer came as a fresh slap: “Nothing really. I just like it when it is 5 pm, so I can go home to feed my dog.”

P.S. It is really our own choice to make a difference or not. It is easier not to, but then it is more rewarding to do it. Your choice, really.

  • Share/Bookmark

Dammsugare

By sibir1us, February 28, 2010

Here is what I did today: (this is a famous swedish desert – my favorite desert ever!)

It has marzipan (almond paste, sugar and butter) on the outside, and some biscuits crumbs mixed with sugar, butter and rum on the inside. Both sides are dipped in chocolate.

I read a story somewhere about how this desert was invented: some chef was bored once and didn’t feel like cleaning his / her pastry cooking table and decided to utilize the leftovers. So, by mixing the ingredients in the right order the final result turned out to be quite edible and was called Dammsugare (swedish for vacuum cleaner).

  • Share/Bookmark

Intellect, IQ, 120 and other demons…

By sibir1us, February 26, 2010

Here is the thing: this morning I received the following email containing a brain teaser.

> >
> > Let’s keep our brains young and flexible. I thought
> > this was fun!  Good Luck!
> >
> >
> > > Look at the math below:
> >
> > >
> > > They say (whoever they are) that only people with an
> > IQ 120 and over
> > > are able to figure this out.
> > >
> > > If:
> > > 2 + 3 = 10
> > >
> > > 7 + 2 = 63
> > > 6 + 5 = 66
> > > 8 + 4 = 96
> >
> > >
> > > Then:
> > > 9 + 7 =  ?
> > >
> > > The number you find out is the password to open the
> > attachment.
> > >
> > > When you solve the problem, and open the attachment:
> > Sign your name,
> > > save it, and  forward it to any more smart people you
> > know, replacing the
> > > original attachment with your new saved updated
> > attachment.
> >
> >

So, first I must say that I disagree with the statement that “only people with an IQ 120 and over are able to figure this out.”  This is not necessarily true. Why not?

The approach: there are several different ways to solve this problem:

  1. you can start staring at the page and try to see a pattern
  2. you get a pen and paper and still try to figure out the problem
  3. you can just “google” it :)

The thing is, that you don’t really need an IQ of 120 to “google” the question. And yes, you will get the correct answer.(The problem’s definition does NOT explicitly restrict “google”-ing!)

The solution: I am not even sure that you need an IQ of 120 to solve the problem by using the first 2 approaches. The problem itself represents a set of statements, which grouped together evaluate as true in response to a pattern, which can be represented by a formula. Now, the line of thought is like this: statement #1 (2 + 3 = 10) evaluates to true in conjunction with N number of patterns (formulas). When you add statement #2, then you limit the applicable patterns to N – n. When you add the statement #3… and so on. And the bottom line is that in a similar problem it is not necessary that you will have only one pattern which responds to all expressions.

So, it is only a matter of time to enumerate all matching patterns for the first statement, subtract the matching patterns from the second statement from the first one and so on… This will be slow, but still the solution will eventually pop up. :)

If you have internet, though… :D

Related Posts with Thumbnails
  • Share/Bookmark

Panorama Theme by Themocracy