Row count per table per environment

Vergeet je niet om regelmatig het aantallen records per tabel per omgevingen te vergelijken?
Er zijn namelijk altijd verschillen, maar kun je ze ook verklaren? 🙂

Row Count per table per environment

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Met de onderstaande dynamische query kun je heel eenvoudig het aantal records tellen. Zo kun je deze query ook aanpassen dat het views of functies gebruikt i.p.v. tabellen.


CREATE PROCEDURE [dbo].[RowCountOnAllTables]
AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE
    @SchemaName VARCHAR(50)
    ,@TableName VARCHAR(250)
    ,@SQL VARCHAR(5000)

DECLARE @Results TABLE
(
    SchemaName VARCHAR(50)
    ,TableName VARCHAR(250)
    ,RecordCount INT
)

DECLARE @CursorResults TABLE
(
    RecordCount INT
)

INSERT INTO @Results
SELECT
    TABLE_SCHEMA AS TableSchema
    ,TABLE_NAME AS TableName
    ,0
FROM INFORMATION_SCHEMA.TABLES t
WHERE TABLE_NAME NOT LIKE '%_Updates'
    AND TABLE_NAME NOT LIKE '%_Errors'
    AND TABLE_NAME NOT LIKE '%_Deleted'
    AND TABLE_SCHEMA != 'logging'
    AND TABLE_SCHEMA != 'maintenance'
    AND t.TABLE_TYPE = 'BASE TABLE'

DECLARE CursorName CURSOR FOR
    SELECT 
        r.SchemaName
        ,r.TableName
    FROM @Results r

OPEN CursorName
FETCH NEXT FROM CursorName INTO @SchemaName, @TableName
WHILE (@@fetch_status = 0)
BEGIN

    SET @SQL = 'SELECT COUNT(*) FROM ['+@SchemaName+'].['+@TableName+']'

    INSERT INTO @CursorResults
    EXEC(@SQL)

    UPDATE @Results
    SET RecordCount = (SELECT RecordCount FROM @CursorResults)
    WHERE SchemaName = @SchemaName
        AND TableName = @TableName

    DELETE FROM @CursorResults

    FETCH NEXT FROM CursorName INTO @SchemaName, @TableName
END

CLOSE CursorName
DEALLOCATE CursorName


SELECT
    SchemaName
    ,TableName
    ,RecordCount
FROM
(
    SELECT
        r.*
    FROM @Results r
) AS r
ORDER BY 1,2
END
GO

 

 

 

 
Nieuwsgierig naar de mogelijkheden van Azure en DevOps binnen uw organisatie?
Neem dan contact met ons op: clint.huijbers@monkeyconsultancy.nl