I have a common search query on a simple table that has only a single covering (nonclustered, not unique) index.
This will use the index:
SELECT @bOK = 1 FROM verify_e1_account WHERE (e1_business_unit = @p_e1_business_unit) AND (e1_gl_acct = @p_e1_gl_acct) AND (e1_cost_code = @p_e1_cost_code));
This will not use the index, but it looks to me like it should:
SELECT @bOK = 1 FROM verify_e1_account WHERE (@p_e1_business_unit IS NULL OR e1_business_unit = @p_e1_business_unit) AND (@p_e1_gl_acct IS NULL OR e1_gl_acct = @p_e1_gl_acct) AND (@p_e1_cost_code IS NULL OR e1_cost_code = @p_e1_cost_code);
How can I make the second version use the index?
Table has a million rows, but all levels are selective.
For a given value, just specifying the business unit returns only 239 rows, specifying both business unit and gl_acct cuts that down to 2 rows. Apparently the optimizer can't see that.
In case it matters, the table is a heap, the covering index is not clustered, there is no clustered index.
Adding separate indexes (and thus statistics) on the separate fields does not fix it, whether or not I also drop the covering index. Fields are char(6),char(8),char(12).
I'd like to understand this, as much as fix it.
SQL Server 2008 SP1 Standard 64-bit.
Thanks,
Josh