SQL查询以查找正在运行的查询和作业

时间:2014-10-30 10:54:30

标签: sql-server etl

我对SQL很新。 我正在使用SQL Server 2008。

我想要的是一个查询,我可以将其放入ETL-Job的计划中,迫使它等到运行给定作业的服务器在没有任何作业或查询运行时处于空闲状态。

我写了一份声明,想知道是否有人可以就我的查询的有效性给我一些意见。我已经测试了它,它似乎有效。

所以我得到了这个诀窍:

declare @retcode INT
DECLARE @JobStatus INT
DECLARE @QueryStatus INT

SET @JobStatus = -1
SET @QueryStatus = -1 

WHILE (@JobStatus != 0 AND @QueryStatus != 1)
BEGIN 

    -- Count all running jobs
        SELECT @JobStatus = count(*)
        FROM
        (
            SELECT sj.name
            ,DATEDIFF(SECOND,aj.start_execution_date,GetDate()) AS Seconds
            FROM msdb..sysjobactivity aj
            JOIN msdb..sysjobs sj on sj.job_id = aj.job_id
            WHERE aj.stop_execution_date IS NULL -- job hasn't stopped running
            AND aj.start_execution_date IS NOT NULL -- job is currently running
            --AND sj.name = 'JobName'
            and not exists( -- make sure this is the most recent run
            select 1
            from msdb..sysjobactivity new
            where new.job_id = aj.job_id
            and new.start_execution_date > aj.start_execution_date )
        ) AS A;


    --only if other jobs are running
    IF (@JobStatus = 0)
        BEGIN
        -- Get QueryStatus zähl alle laufenden Queries die eigene Abfrage wird auch gezählt deswegen oben !=1
            SELECT @QueryStatus = count(*)
            FROM
            (
            SELECT sqltext.TEXT,
            req.session_id,
            req.status,
            req.command,
            req.cpu_time,
            req.total_elapsed_time
            FROM sys.dm_exec_requests req
            CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
            WHERE req.status NOT IN ('background','sleeping','suspended')
            ) AS B;

        END
    WAITFOR DELAY '00:00:02'
END
    -- output = 1 when there are no jobs or queries running
RETURN(1)

0 个答案:

没有答案