如何优化使用多语句表值函数的查询

时间:2015-09-11 19:07:44

标签: sql sql-server sql-server-2008 sqlperformance

所以我的查询需要几秒钟才能运行。

SELECT it.invoiceID, SUM(xgtpp.total + ws.expense) AS invoice_total
FROM Invoices_Timesheets it (NOLOCK)
INNER JOIN Timesheets_WorkSegments tws (NOLOCK)
    INNER JOIN WorkSegments ws (NOLOCK) ON (tws.worksegmentID = ws.ID)
    CROSS APPLY (
        SELECT gtpp.worksegmentID, SUM(gtpp.pay_per_shift) AS total
        FROM dbo.fnGetTotalPerProject(ws.projectID) gtpp
        WHERE (gtpp.worksegmentID = tws.worksegmentID)
        GROUP BY gtpp.worksegmentID
    ) xgtpp
ON (it.timesheetID = tws.timesheetID)
WHERE it.invoiceID = 37
GROUP BY it.invoiceID

使用的表是:

[Invoices]
ID,companyID,userID,projectID,insertDate,submitDate,viewDate,tax

[Invoices_Timesheets]
ID,timesheetID,invoiceID

[WorkSegments]
ID,companyID,userID,projectID,insertDate,startTime,endTime,break,poa,deleteDate,expense

[Timesheets_WorkSegments]
ID,timesheetID,worksegmentID

UDF dbo.fnGetTotalPerProject()只接受一个参数projectID

当我用静态值替换UDF中的ws.projectID时,性能令人难以置信,但只要我使用ws.projectID,性能就会慢下来。

此查询是较大查询的子查询,但绝对是瓶颈。

1 个答案:

答案 0 :(得分:0)

我最终重新编写了dbo.fnGetTotalPerProject每个时间表而不是每个项目。我的下一个目标是针对每个工作段进行优化。