Tuesday, 15 July 2014

SQL to dynamically create filtered statistics

Comment the @sql lines in/out appropriately to drop the statistics after use.
DECLARE @df nvarchar(32),@sql nvarchar(1000)
DECLARE tblcur CURSOR STATIC LOCAL FOR
    select top 2 * from ( SELECT distinct(Id) from MyTable )x
OPEN tblcur
WHILE 1 = 1

BEGIN
    FETCH tblcur INTO @df
    IF @@fetch_status <> 0
        BREAK
    --select @sql = 'DROP STATISTICS MyTable.DF_'+@df;
    select @sql = 'CREATE STATISTICS DF_'+@df+' ON MyTable (Id) WHERE Id = ''' +@df+ ''';';
    --EXEC sp_executesql @sql
    print @sql

END
DEALLOCATE tblcur

No comments:

Post a Comment