I have this SQL query:
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 The above if statement is meant to avoid unnecessary look ups for strings that have already been searched earlier and MatchPercent has been calculated. In that case, it is directly retrieved from Cache table.
Above sql query is basically for one particular column and this same kind of query with just columnName and its value changing is repeated for many other columns in the procedure.
The if Exists check was obviously meant so that query performance could improve however the performance has gone down, probably because of extra checks. Cache table which is actually meant to improve the performance, extra checks have ruined it. Is there a way to simplify above query,please ? Any directions on same will help. Thanks