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
The solution is simpler than I thought it would be (not my original desire but good enough):