SQL count from multiple databases and insert with database name

91 Views Asked by At

Trying to count from multiple databases (which I'm able to do), but I'd like to have the count results in a table near the database name.

My end result would be:

DbName unarchived_measurements
hdb1 10
hdb2 14
hdb3 9

Code:

DECLARE @DT datetime = DATEADD(hour, -3, GETUTCDATE())
DECLARE @DbName VARCHAR(64)
DECLARE @unarchived_measurements_count TABLE (DbName VARCHAR(64), unarchived_measurements INT)

INSERT INTO @unarchived_measurements_count (DbName) 
    SELECT name 
    FROM sys.databases 
    WHERE name LIKE 'H%'

DECLARE db_cursor CURSOR FOR 
    SELECT DbName FROM @unarchived_measurements_count

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @DbName  

WHILE @@FETCH_STATUS = 0
BEGIN 
    EXEC (
        'select count(*) as unarchived_measurements' 
        + ' FROM ' + @DbName + '.dbo.measurements' 
        + ' WHERE date < DATEADD(hour, -3, GETUTCDATE()) and processing_stage = 200'
        )

    FETCH NEXT FROM db_cursor INTO @DbName 
END 

CLOSE db_cursor  
DEALLOCATE db_cursor 

SELECT * FROM @unarchived_measurements_count

I tried with insert statement, but this just add new rows. I tried to update but kept getting errors.

Thanks

1

There are 1 best solutions below

0
Eyal Tal On

The solution is simpler than I thought it would be (not my original desire but good enough):

EXEC (
    'select count(*) as archived_measurements_' **+ @DbName**
    + ' FROM ' + @DbName + '.dbo.measurements' 
    + ' WHERE date > DATEADD(hour, -5, GETUTCDATE())'
    )