Monday, December 15, 2008

MSSQL Rowcount + trending

/* AUTOMATIC TABLE COUNT AND TREND LOGGING */
/* John Minkjan Ciber Nederland */
/* 20081205 v001 intial version */
/* Decalartions */
DECLARE @table_name varchar(250)
DECLARE @strSQL varchar(500)
Declare @SQL varchar(2000)
DECLARE @TABLE_COUNT INT
Declare @TableCount_ID Int
declare @TableCountTrend varchar(50)
/* Part 1 Get the counts */
DECLARE table_cursor CURSOR FOR
SELECT name FROM sys.objects
WHERE type in (N'U')
OPEN table_cursor
FETCH NEXT FROM table_cursor
INTO @table_name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'DECLARE Dyn_cursor CURSOR
FOR SELECT COUNT(*) FROM ' + @table_name
Exec(@SQL)
OPEN Dyn_cursor
FETCH NEXT FROM Dyn_cursor
INTO @TABLE_COUNT
CLOSE Dyn_cursor
DEALLOCATE Dyn_cursor
INSERT INTO [XXXXXX].[dbo].[AUD_TableCount]
([TableName]
,[TableCountDate]
,[TableCount])
VALUES
(@table_name
,GETDATE()
,@TABLE_COUNT)
FETCH NEXT FROM table_cursor
INTO @table_name
END
CLOSE table_cursor
DEALLOCATE table_cursor
/* Part 2 Set the trends */
DECLARE TREND_CURSOR CURSOR FOR
(select t1.TableCount_ID ,
case when t1.tablecount - t2.tablecount = 0 then 'NONE' ELse
case when t1.tablecount - t2.tablecount > 0 then 'UP' else 'DOWN' end end
as TableCountTrend from
(SELECT TableCount_ID,
TableName,
TableCountDate,
TableCount,
ROW_NUMBER() OVER(PARTITION BY TableName ORDER BY TableCountDate ASC) RowVersion
FROM [AMIGO_LOG].[dbo].[AUD_TableCount]) T1,
(SELECT TableName,
TableCountDate,
TableCount,
ROW_NUMBER() OVER(PARTITION BY TableName ORDER BY TableCountDate ASC) RowVersion
FROM [AMIGO_LOG].[dbo].[AUD_TableCount]) T2
where
t1.tablename = t2.tablename and
t1.rowversion-1 = t2.rowversion and
t1.TableCountDate >= getdate()-90)
OPEN TREND_CURSOR
FETCH NEXT FROM TREND_CURSOR
INTO @tableCount_ID, @TableCountTrend
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM TREND_CURSOR
INTO @tableCount_ID, @TableCountTrend
UPDATE [AMIGO_LOG].[dbo].[AUD_TableCount]
SET [TableCountTrend] = @TableCountTrend
WHERE TableCount_ID= @tableCount_ID
END
CLOSE TREND_CURSOR
DEALLOCATE TREND_CURSOR

till next time

No comments: