如何优化此SQL查询
如何优化此代码可以在O(n)中运行,以便在@TollPrice中赋值:如何优化此SQL查询,sql,sql-server,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008 R2,如何优化此代码可以在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 (
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,具有可接受的插入/更新/删除量,则可能需要为car\u subgrp\u 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
如果存在,请删除该值,然后选中@@rowcount。另外,检查是否有正确的索引