如何优化此代码可以在O(n)中运行,以便在@TollPrice中赋值:
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 :(得分: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)
答案 1 :(得分:0)
您的系统是OLAP系统还是PLTP系统? 如果是OLAP或OLTP具有可接受的INSERT / UPDATE / Delete数量,则可能需要为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