简体   繁体   中英

SQL- COUNT all Rows with WHERE condition in all tables in database

I need a query that COUNT all row´s (with WHERE condition) in all tables in a database, where the table_names are unknown. Reason why is: I got a "alarm_logging_system" that creates a new "archive" table every month or so, and automatically names it "AlarmLog(timestamp of last active alarm)"

So I need a query which dynamically search through all tables that exists in the database, COUNTS all row in a column with WHERE condition, and return one single value.

In example I want to get all active alarms, this month, last month, etc. Or a specific time range.

This is an example of a query I wrote to get the count for all active alarms last month

SELECT COUNT(ConditionActive)  
FROM (whole database)???  
WHERE (Acked=0 AND ConditionActive = 1) 
AND (EventTime >= DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0)) 
AND [EventTime] <= DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))))
AS ACTIVE_LAST_MONTH

So what I need is a query, stored_procedure or a dynamic SQL query?

All the tables have the same schema and columns.

Appreciate all help!

This should demonstrate why it is not generally considered a good practice to make multiple copies of the same table and then some aggregate data from the whole collection. This just isn't how relational databases are designed to work.

This is untested because I don't have your table anywhere to work with but this should get it.

declare @SQL nvarchar(max) = ''

--This get a result set of the count for all tables.
select @SQL = @SQL + 'select count(ConditionActive) as MyCount 
    from [' + t.name + '] 
    where Acked = 0 
    AND ConditionActive = 1 
    AND EventTime >= DATEADD(month, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)) 
    and [EventTime] <= DATEADD(day, -1, DATEADD(month, DATEDIFF(month, 0, GETDATE()),0)) UNION ALL'
from sys.tables t

--Now we need the sum of all counts
select @SQL = 'Select sum(MyCount) from (' + LEFT(@SQL, LEN(@SQL) - 10) + ') as x'

select @SQL

--uncomment the line below when you are confident that the dynamic sql is correct.
--exec sp_executesql @SQL

--EDIT-- I took the liberty of expanding the shortcuts in your DATEADD functions. The shortcuts are hard to remember and your were using both mm and m which both mean month. It is generally a better approach to just spell out the word to remove any ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM