ms sql 2012+:有没有更好的方法在子查询中引用外部查询?

时间:2014-03-27 22:12:22

标签: sql-server

当在子查询实例中引用sysJobHistory jh时,此连接语法有效,但有没有更好的方法呢?我知道在mssql2014中,不推荐使用t1.x = t2.x。

    select distinct j.Name as "Job Name", 
        case j.enabled 
            when 1 then 'Enable' 
            when 0 then 'Disable' 
        end as "Job Status", 
        jh.run_date as [Last_Run_Date(YY-MM-DD)] , 
        case jh.run_status 
            when 0 then 'Failed' 
            when 1 then 'Successful' 
            when 2 then 'Retry'
            when 3 then 'Cancelled' 
            when 4 then 'In Progress' 
        end as Job_Execution_Status
      from msdb.dbo.sysJobHistory jh 
       inner join msdb.dbo.sysJobs j
        on j.job_id = jh.job_id
      where jh.run_date =  
        (select max(hi.run_date) 
          from msdb.dbo.sysJobHistory hi 
           where jh.job_id = hi.job_id
             and jh.run_date >= 20140316
         ) 
        and jh.run_status = 3 or j.enabled = 0
        and jh.run_date >= 20140316 

1 个答案:

答案 0 :(得分:0)

扩展我的评论;您使用相关子查询完成它的方式是一种典型的解决方案。我有时采用的另一种方法是对子查询中找到的数据进行排名,然后加入它:

with history as (
    select 
      run_date,
      /* Rank the rows grouped by the job_id */
      row_number() over (partition by job_id order by run_date desc) as rownum
    from msdb.dbo.sysJobHistory 
)
select distinct j.Name as "Job Name", 
    case j.enabled 
        when 1 then 'Enable' 
        when 0 then 'Disable' 
    end as "Job Status", 
    jh.run_date as [Last_Run_Date(YY-MM-DD)] , 
    case jh.run_status 
        when 0 then 'Failed' 
        when 1 then 'Successful' 
        when 2 then 'Retry'
        when 3 then 'Cancelled' 
        when 4 then 'In Progress' 
    end as Job_Execution_Status
  from msdb.dbo.sysJobHistory jh 
   inner join msdb.dbo.sysJobs j
    on j.job_id = jh.job_id
  /* Join to the "newest" instance of the job_id by selecting the correct rank */
   inner join history hi
    on jh.job_id = hi.job_id
    and hi.rownum = 1
  where jh.run_status = 3 or j.enabled = 0
    and jh.run_date >= 20140316