So in our company we have a very large amount of articles. We have a customized search function to search in these articles, and here is a piece of code that generates the a part of the searchquery that needs optimalization.
dtModif = dalDocType.FetchByAnyIdentifier(False, "+")
sb.Append("(SELECT ( ")
For Each row In dtModif.Rows
sb.Append("ISNULL((SELECT -SUM(amount) ")
sb.Append("FROM Sales." & row("TableName") & "Detail ")
sb.Append("WHERE ArticleID = articles.Article.ArticleId ")
sb.Append("AND DATEADD(Year,-1,GETDATE()) < Timestamp ")
sb.Append("),0) ")
sb.Append("+ ")
Next
dtModif = dalDocType.FetchByAnyIdentifier(False, "-")
For Each row In dtModif.Rows
sb.Append("ISNULL((SELECT +SUM(amount) ")
sb.Append("FROM Sales." & row("TableName") & "Detail ")
sb.Append("WHERE ArticleID = articles.Article.ArticleId ")
sb.Append("AND DATEADD(Year,-1,GETDATE()) < Timestamp ")
sb.Append("),0)")
sb.Append("+ ")
Next
sb = sb.Remove(sb.Length - 2, 2)
sb.Append(") )")
I get every article where the stockmodifier is positive (so more sold then returned), and I add the negative sum of all articles where the stockmodifier is negative. In that way I can get the number times that article is sold. (Can be negative).
I want to know now, is there a better way to structure this query? Because this is basically a SELECT over multiple SELECTS, so affects performance in large databases.
Thanks in advance.