BUG in usp_AdaptiveIndexDefrag: When dbScope is set, a new scan is done every time.

Open Beginner friendly
#320 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
74/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Quiet
Tech stack
sql
Domain
databases

Research direction

Start by locating usp_AdaptiveIndexDefrag and the scope-check query referencing dbo.tbl_AdaptiveIndexDefrag_Working and dbo.tbl_AdaptiveIndexDefrag_Stats_Working. Compare the quoted @dbScope value with the database-name values used in the NOT IN subquery. Done means a scoped database does not trigger a rescan on every execution, while forced rescans still behave as intended.

Written by the indexing model from the issue text.

Description

In this piece of code, the query checks if the QUOTED dbScope is NOT in the list of UNQUOTED dbNames that are in the dbo.tbl_AdaptiveIndexDefrag_Working or dbo.tbl_AdaptiveIndexDefrag_Stats_Working tables, and of cause this will never be true. The effect is the
script does a rescan whenever you set the @dbScope parameter.

            /* Check if database scope has changed, if rescan is not being forced */
	IF @forceRescan = 0 AND @dbScope IS NOT NULL -- Specific scope was set
	BEGIN
		IF (SELECT COUNT(DISTINCT [dbID]) FROM dbo.tbl_AdaptiveIndexDefrag_Working) > 1
			OR **QUOTENAME(LOWER(@dbScope)) NOT IN (SELECT DISTINCT LOWER([dbName]) FROM dbo.tbl_AdaptiveIndexDefrag_Working UNION SELECT DISTINCT LOWER(dbName) FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working**)
		BEGIN
			SET @forceRescan = 1
			RAISERROR('Scope has changed. Forcing rescan of single database in scope...', 0, 42) WITH NOWAIT;
		END;
	END;

Suggested fix: add Quotename to the selects in the NOT IN () term:

QUOTENAME(LOWER(@dbScope)) NOT IN (SELECT DISTINCT QUOTENAME(LOWER([dbName])) FROM dbo.tbl_AdaptiveIndexDefrag_Working UNION SELECT DISTINCT QUOTENAME(LOWER(dbName)) FROM dbo.tbl_AdaptiveIndexDefrag_Stats_Working)
BEGIN

Dominant language
Jupyter Notebook
Stars
1.6k
Forks
749
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from microsoft/tigertoolbox

All issues in microsoft/tigertoolbox

Similar issues

More Databases issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.