以下语句执行时间差不多2分钟,当使用相同表格和视图的select语句略有不同时,结果相同:
SELECT
@NEW_CAREER_NUMBER = MAX(a.[career number])
FROM selecthr20.employee.[career history] a
INNER JOIN selecthr20.Employee.[Current Appointments As At Evaluation Date] b
ON a.[appointment number] = b.[appointment number]
INNER JOIN Employee.[BSK Changes in Selected Period] c
ON a.[career number] = c.[primary key number]
INNER JOIN selecthr20.employee.[career history extra detail] d
ON a.[career number] = d.[career number]
AND c.[primary key number] = d.[career number]
where c.[primary key name] = 'Career Number'
and c.[audit date] < (Select max([audit date]) from Employee.[BSK Changes in Selected Period] where [primary key number] = @LATEST_CAREER_NUMBER)
and b.[person number] = @PERSON_ID
&#39; [所选期间的BSK变更] c&#39;是一种观点,其余的是表格。
答案 0 :(得分:-1)
你在d加入时有一个多余的条件 试一试
SELECT
@NEW_CAREER_NUMBER = MAX(a.[career number])
FROM selecthr20.employee.[career history] a
JOIN selecthr20.Employee.[Current Appointments As At Evaluation Date] b
ON b.[appointment number] = a.[appointment number]
and b.[person number] = @PERSON_ID
JOIN selecthr20.employee.[career history extra detail] d
ON d.[career number] = a.[career number]
JOIN Employee.[BSK Changes in Selected Period] c
ON c.[primary key number] = a.[career number]
and c.[primary key name] = 'Career Number'
and c.[audit date] < ( Select max([audit date])
from Employee.[BSK Changes in Selected Period]
where [primary key number] = @LATEST_CAREER_NUMBER );
自然地在连接条件上加上索引
如果你在c join上有一个循环,那么使用一个变量作为审计日期
我会这样做 - 没有什么不好的方面
declare @auditdate DateTime = ( Select max([audit date])
from Employee.[BSK Changes in Selected Period]
where [primary key number] = @LATEST_CAREER_NUMBER );
...
and c.[audit date] < @auditdate