
/*
AUTHOR:  MICHAEL D'SPAIN 3.19.2015
VERSION 1.0
UPDATE STATS JOB THAT UPDATES STATS BASED UPON ROW COUNT PER TABLE.  
		1	-  100K		
		100K-  500K
		500K-  1MIL
		1MIL-  10MIL
		10MIL- 100MIL
		100MIL-250MIL
		250MIl-500MIL
		500MIL-1BIL
		1BIL+

FOR EACH ROWCOUNT DESIGNATION ASSIGN A SCAN PERCENTAGE OF THAT TABLE WHICH ARE SET TO DEFAULT SETTINGS IN THE VARIABLES BELOW.  CHANGE AS NEEDED 

ALSO PERCENT OF CHANGE IN THE TABLE IS CALCULATED.  BASED UPON THAT CHANGE THEN UPDATE THE STATS.   THE THRESHOLD IS SET TO A DEFAULT SETTING BUT CAN BE TWEAKED AS WELL.  

YOU CAN ALSO HAVE TO POPULATE @NUMBER_OF_MIN TO DETERMINE HOW LONG THE JOB WILL RUN. 

ALL UPDATED STATS ARE LOGGED INTO MASTER..STATS_LOG AND ARE TRUNCATED AT EACH EXECUTION OF THE SP.

*/

/*

Create Procedure UpdateStats
@100k		NUMERIC(5,2) = 100,
@500k		NUMERIC(5,2) = 30,
@1MIL		NUMERIC(5,2) = 25,
@10MIL		NUMERIC(5,2) = 15,
@100MIL		NUMERIC(5,2) = 10,
@250MIL		NUMERIC(5,2) = 5,
@500MIL		NUMERIC(5,2) = 2,
@1BIL		NUMERIC(5,2) = .5,
@OVER1BIL	NUMERIC(5,2) = .4,
@PERC_100K		NUMERIC = 5,
@PERC_500K		NUMERIC = 4,
@PERC_1M		NUMERIC = 2,
@PERC_10M		NUMERIC = 1,
@PERC_100M		NUMERIC =.7,
@PERC_250M		NUMERIC = .5,
@PERC_500M		NUMERIC =.4,
@PERC_1B		NUMERC =.4,
@PERC_OVER_1B	NUMERIC = .4
@NUMBER_OF_MIN SMALLINT
as 

*/

/*
GRAB ALL STATS AND RETURN THE FOLLOWING 
	1.  TABLE NAME 
	2.  SCHEMA NAME
	3.  NUMBER OF ROWS IN TABLE
	4.	LAST TIME STATS WERE UPDATED
	5.	PERCENTAGE OF ROWS SAMPLED 
	6.  PERCENTAGE OF ROWS CHANGED 
	7.  NUMBER OF ROWS MODIFIED
*/



--DROP TEMP TABLE IF EXISTS
IF OBJECT_ID('TEMPDB..#STATS') IS NOT NULL
    DROP TABLE #STATS

IF OBJECT_ID('MASTER..STATS_LOG') IS NULL
    CREATE TABLE MASTER..Stats_Log
        (
          ID INT IDENTITY
                 PRIMARY KEY CLUSTERED ,
          SchemaName VARCHAR(100) ,
          TableName VARCHAR(200) ,
          StatsName VARCHAR(200) ,
          Update_stmt VARCHAR(500) ,
          Start_time DATETIME2 ,
          Finish_time DATETIME2
        )

IF EXISTS ( SELECT  *
            FROM    master..stats_log )
    TRUNCATE TABLE master..stats_log

SELECT  sp.stats_id ,
        sc.name AS SchemaName ,
        OBJECT_NAME(s.object_id) AS tablename ,
        s.name AS stats_name ,
        sp.last_updated ,
        sp.rows ,
        sp.rows_sampled ,
        CAST(sp.rows_sampled AS NUMERIC) / CAST(sp.rows AS NUMERIC) * 100 AS Percentage_sampled ,
        CASE WHEN sp.modification_counter = 0 THEN 0
             ELSE CAST(sp.modification_counter AS NUMERIC)
                  / CAST(sp.rows AS NUMERIC) * 100
        END AS Percent_changed ,
        CASE WHEN sp.modification_counter = 0 THEN 'No Modifications'
             ELSE CAST(sp.modification_counter AS VARCHAR(20))
        END AS Modification_counter
INTO    #stats
FROM    sys.stats AS s
        CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
        JOIN sys.tables t ON t.object_id = s.object_id
        JOIN sys.schemas sc ON sc.schema_id = t.schema_id
ORDER BY s.object_id

/*
SELECT * FROM #stats
ORDER BY schemaname 
*/	

/*
REMOVE All STATS THAT HAD A FULL SCAN OR INDEX REBUILD THE PREVIOUS DAY 
*/

DELETE  #stats
WHERE   ( DATEDIFF(DAY, last_updated, CURRENT_TIMESTAMP) IN ( 0, 1 )  
          AND Percentage_sampled = 100
        )  --turn last param of datediff to a variable so you can have stats between current timestamp and variable deleted from #Stats table for deletion.  

/*
REMOVE ALL STATS THAT WERE UPDATED YESTERDAY
this might be over kill.  we might need stuff updated even if it was updated yesterday 
*/

DELETE  #stats
WHERE   DATEDIFF(DAY, last_updated, CURRENT_TIMESTAMP) IN ( 0, 1 ) 
 --turn last param of datediff to a variable so you can have stats between current timestamp and variable deleted from #Stats table for deletion.  

/*
REMOVE ALL SYSTEM OBJECT STATISTICS 
*/

DELETE  #STATS
WHERE   TABLENAME LIKE 'SYS%'

DELETE  #STATS
WHERE   SchemaName = 'CDC'

/*
REMOVE ALL STATS WITH NO MODIFICATIONS
*/

DELETE  #stats
WHERE   Modification_counter = 'NO MODIFICATIONS'

/*
REMOVE ALL EMPTY TABLES 
*/

DELETE  #stats
WHERE   ( last_updated IS NULL
          AND ROWS IS NULL
          AND rows_sampled IS NULL
          AND Percentage_sampled IS NULL
          AND Percent_changed IS NULL
        )

/*
Delete Stats under 100K and less than 5% changed
*/
DELETE #stats
WHERE rows <= 100000 AND Percent_changed <=5 --change to variable

/*
delete stats between 100K and 500K and less than 4% changed 
*/

DELETE #stats
WHERE rows > 100000 AND rows <= 500000 AND Percent_changed <= 4  --change to variable

/*
delete stats between 500k and 1mil and less than 2% changed
*/

DELETE #stats
WHERE rows > 500000 AND rows <= 1000000 AND Percent_changed <= 2  --change to variable

/*
delete stats between 1mil and 10mil and less than 1% changed
*/

DELETE #stats
WHERE rows > 1000000 AND rows <= 10000000 AND Percent_changed <= 1   --change to variable

/*
delete stats between 10mil and 100mil and less than .7% changed
*/

DELETE #stats
WHERE rows > 10000000 AND rows <= 100000000 AND Percent_changed <= .7  --change to variable

/*
delete stats between 100mil and 250mil and less than .5% changed
*/

DELETE #stats
WHERE rows > 100000000 AND rows <= 250000000 AND Percent_changed <= .5  --change to variable

/*
delete stats between 250mil and 500mil and less than .4% changed
*/

DELETE #stats
WHERE rows > 250000000 AND rows <= 500000000 AND Percent_changed <= .4  --change to variable

/*
delete stats between 500mil and 1bil and less than .4% changed
*/

DELETE #stats
WHERE rows > 500000000 AND rows <= 1000000000 AND Percent_changed <= .4  --change to variable

/*
delete stats greater than 1bil and less than .4% changed
*/

DELETE #stats
WHERE rows > 1000000000 AND Percent_changed < .4  --change to variable

/****************************************

BEGIN THE LOOP MAGIC
LOOP THROUGH #STATS TABLE AND UPDATE STATS UPON DEFINED PARAMETERS
INSERT UPDATED STATS INTO STATSLOG TABLE 
	
	CREATE TABLE STATSLOG 
	(SCHEMANAME VARCHAR(100),
	TABLENAME VARCHAR(100),
	STATSNAME VARCHAR(100),
	SCAN_PERCENTAGE INT,
	STATEMENT VARCHAR(500),
	STARTTIME DATETIME2, 
	ENDTIME DATETIME2
	)


****************************************/
/*

CAPTURE CURRENT TIMESTAMP SO AS TO 
ALLOW THE PROCESS TO RUN FOR ONLY A SPECIFIED AMOUNT OF HOURS 

*/

DECLARE @TIME DATETIME2
SET @TIME = CURRENT_TIMESTAMP
/*


CONSIDER ADDING PARAMETERS FOR PERCENTAGE CHANGED TO DELETE AND TO "IF" LOGIC SO PERCENTAGE CHANGED CAN BE TWEAKED ON THE FLY
 
	DECLARE @PERC_100K		NUMERIC = 5
	DECLARE @PERC_500K		NUMERIC = 4
	DECLARE @PERC_1M		NUMERIC = 2
	DECLARE @PERC_10M		NUMERIC = 1
	DECLARE @PERC_100M		NUMERIC =.7
	DECLARE @PERC_250M		NUMERIC = .5
	DECLARE @PERC_500M		NUMERIC =.4
	DECLARE @PERC_1B		NUMERC =.4
	DECLARE @PERC_OVER_1B	NUMERIC = .4

*/
--remove below when changed into a SP
DECLARE @100k NUMERIC = 100
DECLARE @500k NUMERIC = 100
DECLARE @1MIL NUMERIC = 100
DECLARE @10MIL NUMERIC = 20
DECLARE @100MIL NUMERIC = 20
DECLARE @250MIL NUMERIC = 10
DECLARE @500MIL NUMERIC = 10
DECLARE @1BIL NUMERIC = 10
DECLARE @OVER1BIL NUMERIC = 10


DECLARE stats CURSOR LOCAL FAST_FORWARD
FOR
    SELECT  schemaname ,
            tablename ,
            stats_name ,
            last_updated ,
            rows ,
            rows_sampled ,
            Percentage_sampled ,
            Percent_changed ,
            Modification_counter
    FROM    #stats
OPEN stats 
DECLARE @schema VARCHAR(100)
DECLARE @tablename VARCHAR(50)
DECLARE @stats_name VARCHAR(100)
DECLARE @last_update DATETIME
DECLARE @rows BIGINT
DECLARE @rows_sampled INT 
DECLARE @percentage_sampled NUMERIC
DECLARE @percent_changed NUMERIC
DECLARE @Modification_Counter INT
DECLARE @CMD VARCHAR(1000) 
DECLARE @counter INT = ( SELECT COUNT(*)
                         FROM   #stats
                       )
DECLARE @iterator INT = 1 
DECLARE @ID INT
  -- ID for insert into Stats_Log
FETCH NEXT FROM stats INTO @schema, @tablename, @stats_name, @last_update,
    @rows, @rows_sampled, @percentage_sampled, @percent_changed,
    @Modification_Counter
WHILE @@FETCH_STATUS = 0
    BEGIN 
        SET NOCOUNT ON 
        BEGIN TRY  
			--check time at beginning of each iteration of the loop and send to catch block if running outside specified times 
            IF DATEDIFF(mi, @time, CURRENT_TIMESTAMP) >= 1  --change to variable
                BEGIN
                    RAISERROR('YOU RAN OUT OF TIME SUCKA',11,1)
                END
            ELSE
                PRINT CHAR(13) + '/** ' + 'Updating...'
                    + CAST(@iterator AS VARCHAR(6)) + '..of..'
                    + CAST(@counter AS VARCHAR(6)) + '...Statistics' + ' **/'
                    + CHAR(13)
			
            IF ( @rows <= 100000
                 AND @percent_changed >= 5  --change to variable
               )
                BEGIN 
                    INSERT  INTO master..Stats_log
                            ( schemaname ,
                              tablename ,
                              statsname ,
                              Start_time
                            )
                    VALUES  ( @schema ,
                              @tablename ,
                              @stats_name ,
                              CURRENT_TIMESTAMP
                            )
					
                    SELECT  @CMD = 'UPDATE STATISTICS ' + QUOTENAME(@schema)
                            + +'.' + QUOTENAME(@tablename) + '('
                            + QUOTENAME(@stats_name) + ')' + ' with sample '
                            + CAST(@100k AS VARCHAR(10)) + ' PERCENT;'
                    PRINT @cmd
                    EXEC(@cmd) 

				
					
                    SELECT  @id = MAX(id)
                    FROM    master..stats_log
                    WHERE   StatsName = @stats_name
                            AND tablename = @tablename
                            AND Schemaname = @schema
					
                    UPDATE  Master..Stats_log
                    SET     finish_time = CURRENT_TIMESTAMP ,
                            Update_Stmt = @CMD
                    WHERE   id = @id
                            AND StatsName = @stats_name
                            AND tablename = @tablename
                            AND Schemaname = @schema
				
                END 
            ELSE
                IF ( @rows > 100000
                     AND @rows <= 500000
                     AND @percent_changed >= 4   --change to variable
                   )
                    BEGIN 
                        INSERT  INTO master..Stats_log
                                ( schemaname ,
                                  tablename ,
                                  statsname ,
                                  Start_time
                                )
                        VALUES  ( @schema ,
                                  @tablename ,
                                  @stats_name ,
                                  CURRENT_TIMESTAMP
                                )

                        SELECT  @CMD = 'UPDATE STATISTICS '
                                + QUOTENAME(@schema) + +'.'
                                + QUOTENAME(@tablename) + '('
                                + QUOTENAME(@stats_name) + ')'
                                + ' with sample ' + CAST(@500k AS VARCHAR(10))
                                + ' PERCENT;'
                        PRINT @cmd 
                        EXEC(@cmd)

                        SELECT  @id = MAX(id)
                        FROM    master..stats_log
                        WHERE   StatsName = @stats_name
                                AND tablename = @tablename
                                AND Schemaname = @schema
					
                        UPDATE  Master..Stats_log
                        SET     finish_time = CURRENT_TIMESTAMP ,
                                Update_Stmt = @CMD
                        WHERE   id = @id
                                AND StatsName = @stats_name
                                AND tablename = @tablename
                                AND Schemaname = @schema
				
                    END  
                ELSE
                    IF ( @rows > 500000
                         AND @rows <= 1000000
                         AND @percent_changed >= 2   --change to variable
                       )
                        BEGIN 
                            INSERT  INTO master..Stats_log
                                    ( schemaname ,
                                      tablename ,
                                      statsname ,
                                      Start_time
                                    )
                            VALUES  ( @schema ,
                                      @tablename ,
                                      @stats_name ,
                                      CURRENT_TIMESTAMP
                                    )

                            SELECT  @CMD = 'UPDATE STATISTICS '
                                    + QUOTENAME(@schema) + +'.'
                                    + QUOTENAME(@tablename) + '('
                                    + QUOTENAME(@stats_name) + ')'
                                    + ' with sample '
                                    + CAST(@1MIL AS VARCHAR(10)) + ' PERCENT;'
                            PRINT @cmd 
                            EXEC(@cmd)

                            SELECT  @id = MAX(id)
                            FROM    master..stats_log
                            WHERE   StatsName = @stats_name
                                    AND tablename = @tablename
                                    AND Schemaname = @schema
					
                            UPDATE  Master..Stats_log
                            SET     finish_time = CURRENT_TIMESTAMP ,
                                    Update_Stmt = @CMD
                            WHERE   id = @id
                                    AND StatsName = @stats_name
                                    AND tablename = @tablename
                                    AND Schemaname = @schema
                        END 
                    ELSE
                        IF ( @rows > 1000000
                             AND @rows <= 10000000
                             AND @percent_changed >= 1  --change to variable
                           )
                            BEGIN 
                                INSERT  INTO master..Stats_log
                                        ( schemaname ,
                                          tablename ,
                                          statsname ,
                                          Start_time
                                        )
                                VALUES  ( @schema ,
                                          @tablename ,
                                          @stats_name ,
                                          CURRENT_TIMESTAMP
                                        )

                                SELECT  @CMD = 'UPDATE STATISTICS '
                                        + QUOTENAME(@schema) + +'.'
                                        + QUOTENAME(@tablename) + '('
                                        + QUOTENAME(@stats_name) + ')'
                                        + ' with sample '
                                        + CAST(@10MIL AS VARCHAR(10))
                                        + ' PERCENT;'
                                PRINT @cmd 
                                EXEC(@cmd)

                                SELECT  @id = MAX(id)
                                FROM    master..stats_log
                                WHERE   StatsName = @stats_name
                                        AND tablename = @tablename
                                        AND Schemaname = @schema
					
                                UPDATE  Master..Stats_log
                                SET     finish_time = CURRENT_TIMESTAMP ,
                                        Update_Stmt = @CMD
                                WHERE   id = @id
                                        AND StatsName = @stats_name
                                        AND tablename = @tablename
                                        AND Schemaname = @schema
                            END  
                        ELSE
                            IF ( @rows > 10000000
                                 AND @rows <= 100000000
                                 AND @percent_changed >= .7  --change to variable
                               )
                                BEGIN 
                                    INSERT  INTO master..Stats_log
                                            ( schemaname ,
                                              tablename ,
                                              statsname ,
                                              Start_time
                                            )
                                    VALUES  ( @schema ,
                                              @tablename ,
                                              @stats_name ,
                                              CURRENT_TIMESTAMP
                                            )

                                    SELECT  @CMD = 'UPDATE STATISTICS '
                                            + QUOTENAME(@schema) + +'.'
                                            + QUOTENAME(@tablename) + '('
                                            + QUOTENAME(@stats_name) + ')'
                                            + ' with sample '
                                            + CAST(@100MIL AS VARCHAR(20))
                                            + ' PERCENT;'
                                    PRINT @cmd 
                                    EXEC(@cmd)

                                    SELECT  @id = MAX(id)
                                    FROM    master..stats_log
                                    WHERE   StatsName = @stats_name
                                            AND tablename = @tablename
                                            AND Schemaname = @schema
					
                                    UPDATE  Master..Stats_log
                                    SET     finish_time = CURRENT_TIMESTAMP ,
                                            Update_Stmt = @CMD
                                    WHERE   id = @id
                                            AND StatsName = @stats_name
                                            AND tablename = @tablename
                                            AND Schemaname = @schema
                                END  
                            ELSE
                                IF ( @rows > 100000000
                                     AND @rows <= 250000000
                                     AND @percent_changed > .5 --change to variable
                                   )
                                    BEGIN 
                                        INSERT  INTO master..Stats_log
                                                ( schemaname ,
                                                  tablename ,
                                                  statsname ,
                                                  Start_time
                                                )
                                        VALUES  ( @schema ,
                                                  @tablename ,
                                                  @stats_name ,
                                                  CURRENT_TIMESTAMP
                                                )

                                        SELECT  @CMD = 'UPDATE STATISTICS '
                                                + QUOTENAME(@schema) + +'.'
                                                + QUOTENAME(@tablename) + '('
                                                + QUOTENAME(@stats_name) + ')'
                                                + ' with sample '
                                                + CAST(@250MIL AS VARCHAR(20))
                                                + ' PERCENT;'
                                        PRINT @cmd 
                                        EXEC(@cmd)

                                        SELECT  @id = MAX(id)
                                        FROM    master..stats_log
                                        WHERE   StatsName = @stats_name
                                                AND tablename = @tablename
                                                AND Schemaname = @schema
					
                                        UPDATE  Master..Stats_log
                                        SET     finish_time = CURRENT_TIMESTAMP ,
                                                Update_Stmt = @CMD
                                        WHERE   id = @id
                                                AND StatsName = @stats_name
                                                AND tablename = @tablename
                                                AND Schemaname = @schema
                                    END
                                ELSE
                                    IF ( @rows > 250000000
                                         AND @rows <= 500000000
                                         AND @percent_changed > .4  --change to variable
                                       )
                                        BEGIN 
                                            INSERT  INTO master..Stats_log
                                                    ( schemaname ,
                                                      tablename ,
                                                      statsname ,
                                                      Start_time
                                                    )
                                            VALUES  ( @schema ,
                                                      @tablename ,
                                                      @stats_name ,
                                                      CURRENT_TIMESTAMP
                                                    )

                                            SELECT  @CMD = 'UPDATE STATISTICS '
                                                    + QUOTENAME(@schema)
                                                    + +'.'
                                                    + QUOTENAME(@tablename)
                                                    + '('
                                                    + QUOTENAME(@stats_name)
                                                    + ')' + ' with sample '
                                                    + CAST(@500MIL AS VARCHAR(20))
                                                    + ' PERCENT;'
                                            PRINT @cmd 
                                            EXEC(@cmd)

                                            SELECT  @id = MAX(id)
                                            FROM    master..stats_log
                                            WHERE   StatsName = @stats_name
                                                    AND tablename = @tablename
                                                    AND Schemaname = @schema
					
                                            UPDATE  Master..Stats_log
                                            SET     finish_time = CURRENT_TIMESTAMP ,
                                                    Update_Stmt = @CMD
                                            WHERE   id = @id
                                                    AND StatsName = @stats_name
                                                    AND tablename = @tablename
                                                    AND Schemaname = @schema
                                        END  
                                    ELSE
                                        IF ( @rows > 500000000
                                             AND @rows <= 1000000000
                                             AND @percent_changed > .4  --change to variable
                                           )
                                            BEGIN 
                                                INSERT  INTO master..Stats_log
                                                        ( schemaname ,
                                                          tablename ,
                                                          statsname ,
                                                          Start_time
                                                        )
                                                VALUES  ( @schema ,
                                                          @tablename ,
                                                          @stats_name ,
                                                          CURRENT_TIMESTAMP
                                                        )

                                                SELECT  @CMD = 'UPDATE STATISTICS '
                                                        + QUOTENAME(@schema)
                                                        + +'.'
                                                        + QUOTENAME(@tablename)
                                                        + '('
                                                        + QUOTENAME(@stats_name)
                                                        + ')'
                                                        + ' with sample '
                                                        + CAST(@1BIL AS VARCHAR(20))
                                                        + ' PERCENT;'
                                                PRINT @cmd 
                                                EXEC(@cmd)

                                                SELECT  @id = MAX(id)
                                                FROM    master..stats_log
                                                WHERE   StatsName = @stats_name
                                                        AND tablename = @tablename
                                                        AND Schemaname = @schema
					
                                                UPDATE  Master..Stats_log
                                                SET     finish_time = CURRENT_TIMESTAMP ,
                                                        Update_Stmt = @CMD
                                                WHERE   id = @id
                                                        AND StatsName = @stats_name
                                                        AND tablename = @tablename
                                                        AND Schemaname = @schema
                                            END 
                                        ELSE
                                            IF ( @rows > 1000000000
                                                 AND @percent_changed > .4  --change to variable
                                               )
                                                BEGIN 
                                                    INSERT  INTO master..Stats_log
                                                            ( schemaname ,
                                                              tablename ,
                                                              statsname ,
                                                              Start_time
                                                            )
                                                    VALUES  ( @schema ,
                                                              @tablename ,
                                                              @stats_name ,
                                                              CURRENT_TIMESTAMP
                                                            )

                                                    SELECT  @CMD = 'UPDATE STATISTICS '
                                                            + QUOTENAME(@schema)
                                                            + +'.'
                                                            + QUOTENAME(@tablename)
                                                            + '('
                                                            + QUOTENAME(@stats_name)
                                                            + ')'
                                                            + ' with sample '
                                                            + CAST(@OVER1BIL AS VARCHAR(20))
                                                            + ' PERCENT;'
                                                    PRINT @cmd 
                                                    EXEC(@cmd)

                                                    SELECT  @id = MAX(id)
                                                    FROM    master..stats_log
                                                    WHERE   StatsName = @stats_name
                                                            AND tablename = @tablename
                                                            AND Schemaname = @schema
					
                                                    UPDATE  Master..Stats_log
                                                    SET     finish_time = CURRENT_TIMESTAMP ,
                                                            Update_Stmt = @CMD
                                                    WHERE   id = @id
                                                            AND StatsName = @stats_name
                                                            AND tablename = @tablename
                                                            AND Schemaname = @schema
                                                END  
                                            ELSE
                                                BEGIN 
                                                    PRINT CHAR(13)
                                                        + '/*******************/'
                                                        + CHAR(13)
                                                        + 'Did not meet specified parameters '
                                                        + @tablename + '..'
                                                        + @stats_name
                                                        + '..rows..'
                                                        + CAST(@rows AS VARCHAR(20))
                                                        + '..percent_changed  '
                                                        + CAST(@percent_changed AS VARCHAR(20))
                                                        + CHAR(13)
                                                        + '/********************/'
                                                        + CHAR(13)
	
                                                    INSERT  INTO master..Stats_log
                                                            ( schemaname ,
                                                              tablename ,
                                                              statsname ,
                                                              update_stmt ,
                                                              Start_time ,
                                                              finish_time
															)
                                                    VALUES  ( @schema ,
                                                              @tablename ,
                                                              @stats_name ,
                                                              'Did not meet specified parameters ' ,
                                                              CURRENT_TIMESTAMP ,
                                                              CURRENT_TIMESTAMP
															)
                                                END


            SET @iterator = @iterator + 1

            FETCH NEXT FROM stats INTO @schema, @tablename, @stats_name,
                @last_update, @rows, @rows_sampled, @percentage_sampled,
                @percent_changed, @Modification_Counter
        END TRY 
        BEGIN CATCH 
            SELECT  ERROR_MESSAGE() AS ErrorMessage
            BREAK 
        END CATCH
    END 
CLOSE stats 
DEALLOCATE stats

--DROP TABLE #stats

--SELECT * FROM master..stats_log





