2015-03-03 102 views
0

我有這樣的SQL查詢的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已計算出的字符串不必要的外觀窗口。在這種情況下,它直接從緩存表中檢索。

上面的sql查詢基本上是針對一個特定的列,並且該查詢只有columnName,並且其值會隨着該過程中的許多其他列而重複更改。

if Exists檢查顯然意味着查詢性能可以提高,但是性能下降可能是由於額外的檢查。 緩存表實際上是爲了提高性能,額外的檢查已經毀了它。 請問有沒有辦法簡化上述查詢?任何方向相同將有所幫助。 感謝

+0

順便說一句:可怕的語法。 – reporter 2015-03-03 13:19:56

+1

您是否考慮過在數據被修改時從緩存中刪除行?這會減少你現在要檢查時間字段的I/O。此外,對於過去24小時內的同一事件,這似乎至少是第3個問題,也許您可​​以更新原始問題... – 2015-03-03 13:22:02

回答

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 . . . 
+0

謝謝。但是,您可以指定是否在這些列上建議聚集索引或非聚集索引? – Simran 2015-03-03 13:17:39

+1

@SImran。 。 。除非另有指定,否則索引是非羣集的。聚簇索引通常用於主鍵。 – 2015-03-05 01:22:32

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