SQL查询性能如果存在

时间:2015-03-03 13:10:10

标签: sql sql-server database-performance sqlperformance

我有这个SQL查询:

IF NOT EXISTS (SELECT TOP 1 RowId
               FROM   dbo.Cache AS C
               WHERE  StringSearched = @pcpnpi
                      AND colName = 'pcpnpi'
                      AND ModifiedAt > (SELECT ModifiedAt
                                        FROM   dbo.Patients AS p
                                        WHERE  P.RowID = C.RowID))
  BEGIN
      SELECT @constVal = FunctionWeight
      FROM   dbo.FunctionWeights
      WHERE  FunctionWeights.FunctionId = 33;

      INSERT INTO #Temp2
                  (RowNumber,ValFromUser,ColumnName,ValFromFunc,
                   FuncWeight,percentage)
      SELECT RowNumber,@pcpnpi,'pcpnpi',PercentMatch,
             @constVal,PercentMatch * @constVal
      FROM   dbo.Matchpcpnpi (@pcpnpi);
  END
ELSE
  BEGIN
      INSERT INTO #Temp2
                  (RowNumber,ValFromUser,ColumnName,Percentage)
      SELECT RowId,StringSearched,ColName,PercentMatch
      FROM   dbo.Cache AS C
      WHERE  StringSearched = @pcpnpi
             AND colName = 'pcpnpi'
             AND ModifiedAt > (SELECT ModifiedAt
                               FROM   dbo.Patients AS p
                               WHERE  P.RowID = C.RowID)
  END 

上述if语句旨在避免对先前已搜索过的字符串进行不必要的查找,并计算MatchPercent。在这种情况下,它直接从Cache表中检索。

上面的sql查询基本上是针对一个特定的列,并且对于该过程中的许多其他列,重复这种仅具有columnName并且其值更改的查询。

if Exists检查显然意味着查询性能可以改善,但性能下降,可能是因为额外的检查。 缓存表实际上是为了提高性能,额外的检查已经破坏了它。 有没有办法简化上面的查询,好吗?任何指示都有帮助。 感谢

2 个答案:

答案 0 :(得分:2)

首先根据存在条件插入#temp2。如果插入记录计数为零,则执行另一个插入。试试这个。

INSERT INTO #Temp2
            (RowNumber,ValFromUser,ColumnName,Percentage)
SELECT RowId,StringSearched,ColName,PercentMatch
FROM   dbo.Cache AS C
WHERE  StringSearched = @pcpnpi
       AND colName = 'pcpnpi'
       AND ModifiedAt > (SELECT ModifiedAt
                         FROM   dbo.Patients AS p
                         WHERE  P.RowID = C.RowID)

IF @@ROWCOUNT = 0
  BEGIN
      SELECT @constVal = FunctionWeight
      FROM   dbo.FunctionWeights
      WHERE  FunctionWeights.FunctionId = 33;

      INSERT INTO #Temp2
                  (RowNumber,ValFromUser,ColumnName,ValFromFunc,
                   FuncWeight,percentage)
      SELECT RowNumber,@pcpnpi,'pcpnpi',PercentMatch,
             @constVal,PercentMatch * @constVal
      FROM   dbo.Matchpcpnpi (@pcpnpi)
  END 

答案 1 :(得分:1)

首先,请考虑exists中的此查询:

select Top 1 RowId
from dbo.Cache as C
where StringSearched = @pcpnpi and
      colName = 'pcpnpi' and
      ModifiedAt > ( Select ModifiedAt FROM dbo.Patients p WHERE P.RowID = C.RowID))

为了提高性能,您需要cache(StringSearched, colName, ModifiedAt, RowId)Patients(RowId)上的索引。

但是,您正在运行此查询两次。我建议更像一个结构:

declare @RowId . . . ;  -- I don't know the type

select Top 1 @RowId = RowId
from dbo.Cache as C
where StringSearched = @pcpnpi and
      colName = 'pcpnpi' and
      ModifiedAt > ( Select ModifiedAt FROM dbo.Patients p WHERE P.RowID = C.RowID));

if (@RowId) is null . ..
else . . .