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;