The below statement is taking almost 2 minutes to execute, when a slightly different select statement using the same tables and views with the same results is taking half that:
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
'[BSK changes in Selected Period] c' is a view, the rest are tables.
You had a redundant condition on the d join
Give this a try
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 );
Naturally put an index on the join conditions
And if you have a loop on the c join then use a variable for audit date
I would just do this - there is very little down side
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.