Wednesday, November 6, 2024

I have multiple databases with the same table structure, and each database name starts with 'U'. I want to find the row count of the Traces table in each of these databases. Could you provide a SQL script that loops through each database starting with 'U', checks if the Traces table exists, and retrieves the row count for it in each database?

 USE master;

DECLARE @DatabaseName NVARCHAR(128);

DECLARE @sql NVARCHAR(MAX);


-- Cursor to iterate over each database starting with "U"

DECLARE db_cursor CURSOR FOR

SELECT name 

FROM sys.databases

WHERE name LIKE 'U%'  -- Filters databases starting with "U"

  AND state_desc = 'ONLINE'; -- Only includes online databases


-- Open the cursor

OPEN db_cursor;

FETCH NEXT FROM db_cursor INTO @DatabaseName;


-- Loop through each database

WHILE @@FETCH_STATUS = 0

BEGIN

    -- Construct the dynamic SQL for each database

    SET @sql = 'USE ' + QUOTENAME(@DatabaseName) + ';

                IF EXISTS (SELECT 1 FROM ' + QUOTENAME(@DatabaseName) + '.sys.tables WHERE name = ''Traces'')

                BEGIN

                    SELECT ''' + @DatabaseName + ''' AS DatabaseName, 

                           COUNT(*) as rowscount 

                    FROM ' + QUOTENAME(@DatabaseName) + '.dbo.Traces;

                END';

    

    -- Execute the dynamic SQL

    EXEC sp_executesql @sql;


    -- Move to the next database

    FETCH NEXT FROM db_cursor INTO @DatabaseName;

END


-- Close and deallocate the cursor

CLOSE db_cursor;

DEALLOCATE db_cursor;