Create table #tmptble(RuleId, SubjectId, RID, Date)
Insert into #tmptble(RuleId,SubjectId, RID, Date)
Select RuleTable.RuleId, RuleTable.SubjectId, KeyTable.RID, KeyTable.ParentId
FROM RuleTable INNER JOIN KeyTable
ON KeyTable.RID = RuleTable.RID
这个查询很慢。我在 KeyTable 上的 RID 上有一个聚集索引,在 RuleTable 上的 RuleId 上有一个聚集索引,在 RuleTable 上的 RuleId+SubjectId 上有唯一的非聚集索引。(RuleTable 用于其他各种地方)
在上面的查询中,如果我引入一个 where 子句,例如
Insert into #tmptble(RuleId,SubjectId, RID, Date)
Select RuleTable.RuleId, RuleTable.SubjectId, KeyTable.RID, KeyTable.ParentId
FROM RuleTable INNER JOIN KeyTable
ON KeyTable.RID = RuleTable.RID
WHERE KeyTable.RID = @RID -- @RID is passed into the storedproc
运行时间减少 > 50%。但问题是我使用原始表结果不带WHERE
子句的方式如下
WITH ResourceTree AS
(
SELECT
#tmptble.RuleId AS [RuleId],
#tmptble.SubjectId AS [SubjectRecId],
#tmptble.RId AS [RId],
#tmptble.ParentID AS [ParentID]
FROM #tmptble WHERE #tmptble.SubjectId = @SubjectId
AND #tmptble.RId = @RId
UNION ALL
-- Recursive step
-- Note that the recursive step uses the results from original #tmptable
SELECT
#tmptble.RuleId AS [RuleId],
#tmptble.SubjectId AS [SubjectId],
#tmptble.RId AS [RId],
#tmptble.ParentID AS [ParentID]
FROM #tmptble INNER JOIN ResourceTree RT
ON RT.ParentID = #tmptble.RId
)
SELECT *
FROM ResourceTree
有没有办法优化这个查询?任何关于索引或递归方式的建议都会有所帮助