我在存储过程中有这个查询:
SELECT
*,
ISNULL(dbo.ReturnShortageByItemCodeLinePackage(LineId, TestPackageId, MaterialDescriptionId), 0) AS Shortage
FROM
dbo.ViewMTO
我在查询中使用一个函数来计算整数值,如下所示:
ALTER FUNCTION [dbo].[ReturnShortageByItemCodeLinePackage]
(@lineId int,@testpackId int, @MaterialDescriptionId int)
RETURNS float
AS
BEGIN
DECLARE @shortageQuantity float
DECLARE @MIVQuantity float
DECLARE @totalQuantity float
DECLARE @spoolQuantity float
DECLARE @ExistInSiteQuantity float
DECLARE @BeforeDoneQuantity float
SELECT
@totalQuantity = Quantity,
@spoolQuantity = QuantitySpool,
@ExistInSiteQuantity = QuantityExistInSite,
@BeforeDoneQuantity = QuantityBeforeDone
FROM
[SPMS2].[dbo].Materials
WHERE
LineId = @lineId
AND TestPackageId = @testpackId
AND MaterialDescriptionId = @MaterialDescriptionId
SELECT
@MIVQuantity = SUM(QuantityDeliver)
FROM
MaterialIssueVoucherDetails miv
JOIN
MaterialRequestContractorDetails mrc ON miv.MaterialRequestContractorDetailId = mrc.Id
WHERE
TestPackageId = @testpackId
AND LineId = @lineId
AND miv.MaterialDescriptionId = @MaterialDescriptionId
IF @MIVQuantity IS NULL
BEGIN
SET @MIVQuantity = 0
END
SET @shortageQuantity = @totalQuantity - (@BeforeDoneQuantity + @ExistInSiteQuantity + @spoolQuantity + @MIVQuantity)
RETURN round(@shortageQuantity, 3)
END
我的查询在3分钟内执行,对我的用户来说是灾难性的!有没有更好的解决方案?
答案 0 :(得分:1)
我可以推荐三件事:
一个。以下一行..
SELECT @totalQuantity= ...
FROM [SPMS2].[dbo].Materials
这是通过链接服务器连接访问不同的数据库吗?这种连接有多快?
B中。您的SP包含两个 SELECT语句。其中哪一个是瓶颈? 您可以添加一些PRINT语句来显示每个语句的启动时间:
PRINT convert(nvarchar, GetDate(), 108) + ' This is the time !'
℃。尝试在我的网页上运行SQL show,这将突出显示缺少的索引。
希望这有帮助。
答案 1 :(得分:0)
将Scaler函数转换为Table-Valued函数,然后将函数放在FROM子句中以进行LEFT JOIN。检查执行计划以找到任何警告。
Testing performance of Scalar vs Table-valued functions in sql server