2015-04-08 130 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