Search This Blog

Showing posts with label SQL JOBS. Show all posts
Showing posts with label SQL JOBS. Show all posts

SQL JOBS:Query to find last run status of scheduled Jobs

Here is a T-SQL query to find the last run status of all the scheduled jobs in SQL Server.
This query will be handy when you are not able to access the "Job Activity Monitor"

SELECT SUSER_NAME(members.role_principal_id) AS [ServerRole]
   ,logins.name AS 'RoleMember'
   ,'EXEC sp_addsrvrolemember ''' +logins.name+''', '''+
   SUSER_NAME(members.role_principal_id)+'''' AS [Command to add role members]
FROM sys.server_role_members members, sys.server_principals logins
WHERE members.role_principal_id >=3 AND members.role_principal_id <=10 AND
members.member_principal_id = logins.principal_id
and logins.name <>'sa'


SQL JOB:SQL Query to find currently running jobs and duration


 

Here is a T-SQL query to find the currently executing jobs.

The output of this query will be the list of jobs that are currently running along with the number of seconds

 it is been running.


SELECT  J.name as Running_Jobs,  
  JA.Start_execution_date As Starting_time,
        datediff(ss, JA.Start_execution_date,getdate()) as [Has_been_running(in Sec)]
FROM msdb.dbo.sysjobactivity JA
JOIN msdb.dbo.sysjobs J
ON J.job_id=JA.job_id
WHERE job_history_id is null
      AND start_execution_date is NOT NULL
ORDER BY start_execution_date

How to invoke a SQL job from another Job present on a different instance

For invoking an SQL Server Job from another Job which is present on a different instance, we have different 
ways like
  1. Create a Linked server and use msdb..sp_start_job to start the job
  2. Using xp_cmdshell
  3. Using SQLCMD Operating system command
In most of the SQL Server instances the xp_cmdshell will be disable due to security reasons and creating 
linked server is time consuming.

So, the most easy approach would be to use the SQLCMD Operating system command.
Create a new step in the job with the type "Operating System (CmdExec)" and use the below command
SQLCMD -S <Server Name> -E -Q "EXEC msdb..sp_start_job <Job Name>"