I have the below code to pull the row and column counts from each table within a database (e.g., db1). But I have several databases (e.g., db1, db2 etc.) , so manually updating the database name in the USE statement for every run isn't very convenient. Is there a way to pass a list of database names in a cursor (or something else that allows iteration) and then run the below query for every database in the list, appending the results from each run? I can get the list of database names from this query select name from master.dbo.sysdatabases where name like '%db%'.
USE [db1]
;with [rowCount] as
(
    SELECT  DB_NAME() as [DB_Name],
            QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName],
            SUM(sPTN.Rows) AS [RowCount]
    FROM    SYS.OBJECTS AS sOBJ
    INNER JOIN SYS.PARTITIONS AS sPTN
        ON sOBJ.object_id = sPTN.object_id
    WHERE
        sOBJ.type = 'U'
        AND sOBJ.is_ms_shipped = 0x0
        AND index_id < 2 -- 0:Heap, 1:Clustered
    GROUP BY      
        sOBJ.schema_id
        ,sOBJ.name
)
,columnCount as
(
    select 
        QUOTENAME(col.TABLE_SCHEMA) + '.' + QUOTENAME(col.TABLE_NAME) AS [TableName],
        count(*) as ColumnCount
    from INFORMATION_SCHEMA.COLUMNS col
    inner join INFORMATION_SCHEMA.TABLES tbl
        on col.TABLE_SCHEMA = tbl.TABLE_SCHEMA
        and col.TABLE_NAME = tbl.TABLE_NAME
        and tbl.TABLE_TYPE <> 'view'
    group by 
        QUOTENAME(col.TABLE_SCHEMA) + '.' + QUOTENAME(col.TABLE_NAME)
)
select r.[DB_Name], r.TableName, r.[RowCount], c.ColumnCount
from [rowCount] r
inner join columnCount c
    on r.TableName = c.TableName
ORDER BY r.[TableName]
 
    