使用CROSS APPLY进行慢查询

时间:2017-11-09 12:02:13

标签: sql cross-apply

我有以下SQL代码需要几秒钟才能执行:

SELECT instance.startdate
      ,instance.enddate 
FROM (select mr.id 
      FROM meeting_recurrence AS mr 
      inner JOIN meeting_details md ON md.id = mr.meeting_template_id 
      WHERE host_user_id=17) AS p 
CROSS APPLY GetRecurrenceMeetingInstances(p.id,'2018-11-09 11:00:00','2018-11-09 15:00:00') AS instance  
WHERE 21015 IS NOT NULL 
AND instance.meetingid <> 21015

内部选择(select mr.id FROM meeting_recurrence...)立即在上面的示例中返回,有两个ID。

分别使用这两个ID运行GetRecurrenceMeetingInstances(),立即返回空结果。

与单独运行相比,为什么运行整个语句需要这么长时间?

执行计划图片:https://imgur.com/a/3Ydym

1 个答案:

答案 0 :(得分:0)

似乎CROSS APPLY正在调用GetRecurrenceMeetingInstances()比我想象的要多得多。我通过首先在内部变量中保存内部选择来解决问题:

DECLARE @innerresult table(meetingid int)
INSERT INTO @innerresult(meetingid) (select mr.id FROM meeting_recurrence AS mr inner JOIN meeting_details md ON md.id = mr.meeting_template_id 
    WHERE host_user_id=17)

INSERT INTO @timeslots (startdate,enddate) 
    SELECT instance.startdate,instance.enddate 
    FROM (select meetingid FROM @innerresult) AS p 
    CROSS APPLY GetRecurrenceMeetingInstances(p.meetingid,'2018-11-09 11:00:00','2018-11-09 15:00:00') AS instance