我如何优化此 SQL 查询
How can I optimize this SQL query
我如何优化此代码可以 运行 在 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
此处无需验证是否存在:
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)
你的系统是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
我如何优化此代码可以 运行 在 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
此处无需验证是否存在:
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)
你的系统是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