Wednesday, May 8, 2013

Can I prevent SQL Server from consolidating histogram steps in statistics?

Might be useful for anybody willing to investigate the problem:


In order to check queries for all intervals I’ve used the following script which just iterates over dates present in the FactTable. There is definitely an easier way, but it was good enough for me.



DECLARE @curDatum INT
DECLARE @tomorrow date

DECLARE @curDatumVersion INT
DECLARE @tomorrowVersion INT

DECLARE date_cursor CURSOR FOR
SELECT datumid/100 FROM dbo.FaktMVaR GROUP BY datumid/100 ORDER BY datumid/100

OPEN date_cursor

FETCH NEXT FROM date_cursor INTO @curDatum

WHILE @@FETCH_STATUS = 0
BEGIN
SET @tomorrow = DATEADD(DAY, 1, cast(cast(@curDatum as varchar(10)) as date))

SET @curDatumVersion = @curDatum*100
SET @tomorrowVersion = cast(convert(varchar(8),@tomorrow,112) as int) * 100

SELECT * FROM
dbo.FaktMVaR f
INNER JOIN dbo.DimDatum AS dd
ON f.DatumID = dd.DatumID
AND dd.LastVersion = 1
WHERE dd.DatumID >= @curDatumVersion
AND dd.DatumID < @tomorrowVersion
OPTION(RECOMPILE)

FETCH NEXT FROM date_cursor INTO @curDatum
END
CLOSE date_cursor;
DEALLOCATE date_cursor



I’ve started SQL Server Profiler and monitored the ‘Showplan XML Statistics Profile’ event. Check the IntegerData column, most of the time you will see alternating 9999 (test query) and 1 (cursor fetch), but sometimes there will be “1, 1, 1” – that’s a query with a wrong cardinality estimate (reproducible with or without filtered statistics).

No comments:

Post a Comment