2015-04-08 96 views
0

如何优化这个代码可以为O(n)的分配值@TollPrice运行:如何优化这个SQL查询

IF (EXISTS (SELECT TollPrice 
      FROM Car_TaxInfo 
      WHERE (car_subgrp_id = @Kind) AND (Sal = @Sal))) 
    BEGIN 
     SELECT @TollPrice = TollPrice 
     FROM Car_TaxInfo 
     WHERE  (car_subgrp_id = @Kind) AND (Sal = @Sal) 
     SET @IsExistToll = 1 
    END 
ELSE 
    BEGIN 
     SET @IsExistToll = 0 
    END 
+0

删除if存在,只需选择该值并在其后面检查@@ rowcount。另外,检查是否有正确的索引 –

+0

@JamesZ谢谢;) –

回答

2

你并不需要在这里验证是否存在:

SET @TollPrice = NULL --this is mandatory. If @TollPrice contains some value then it will retain that value after below statement if there will be no matching rows. 

SELECT @TollPrice = TollPrice 
FROM Car_TaxInfo 
WHERE (car_subgrp_id = @Kind) AND (Sal = @Sal) 

IF @TollPrice IS NOT NULL 
    SET @IsExistToll = 1 
ELSE 
    SET @IsExistToll = 0 

如果TollPrice可以NULL本身,那么你可以使用@@ROWCOUNT

SELECT @TollPrice = TollPrice 
FROM Car_TaxInfo 
WHERE (car_subgrp_id = @Kind) AND (Sal = @Sal) 

IF @@ROWCOUNT > 0 
    SET @IsExistToll = 1 
ELSE 
    SET @IsExistToll = 0 

夏娃您可以执行以下操作:

SET @IsExistToll = 0 

SELECT @TollPrice = TollPrice, @IsExistToll = 1 
FROM Car_TaxInfo 
WHERE (car_subgrp_id = @Kind) AND (Sal = @Sal) 
0

您的系统是OLAP系统还是PLTP系统? 如果它是OLAP或者它是具有可接受数量的INSERT/UPDATE/Delete的OLTP,则可能需要为car_subgrp_id和Sal列添加索引。 在IF select子句中,您可以将您的查询与TOP 1结合起来,并用此新查询替换EXISTS。我的意思是您的新查询可能如下所示:

Declare @tPrice INT 
IF (SELECT TOP 1 @tPrice=TollPrice 
     FROM Car_TaxInfo 
     WHERE (car_subgrp_id = @Kind) AND (Sal = @Sal) IS NOT NULL) 
    SET @IsExistToll = 1 
ELSE 
    SET @IsExistToll = 0