I have a database with hundreds of tables, some having a column named column1
. I want to count occurrences of a specific value in these tables like this:
Table | Count
-------|------
table1 | 0
table2 | 5
...
First part (finding list of tables) is done using the code from here. But I don't know how to put these names in a query. As explained in another question, table names and column names should be static in a static query. What I get from that answer is that I have to generate some tsql like:
SELECT 'table1' AS [Table], count(*) AS [Count] FROM table1 WHERE column1 = somevalue
UNION SELECT 'table2' AS [Table], count(*) AS [Count] FROM table2 WHERE column1 = somevalue
UNION ...
and then run it using EXEC or sp_executesql.
So, are there any other options to automate this?