I want to count all the columns in a database table and union the counts together using an iterative method for 15 columns instead of what I have shown in the example.
i.e.
select count(columnname1)
from schema.tablename
where columnname1 is not null and datasource = xxx
union all
select count(columnname2)
from schema.tablename
where columnname1 is not null and datasource = xxx
union all
....
The result should returns a count per columns for 15 columns and stored in a table.
3条答案
按热度按时间kknvjkwl1#
A variation of the dynamic sql approach which outputs 3 columns (the count, the column name and the table name). You can specify the table name(s) you want in the where clause and you can optionally also filter which columns you want to consider.
This variant does not include "where [colname] IS NOT NULL" as this is redundant given the
COUNT()
will just ignore NULL values and it is unlikely that these where clauses will enhance overall performance as table scans are likely in all or most cases.see example: https://dbfiddle.uk/EAez4OGR
niknxzdl2#
You can use a dynamic SQL query to achieve this. Here’s an example that you can modify to fit your needs:
This code generates a dynamic SQL query that counts the non-null values in each column of the
schema.tablename
table whose name starts withcolumnname
. The results are then combined usingUNION ALL
. You can modify theWHERE
clause in theSELECT
statement to include only the columns you want to count.bgtovc5b3#
Here's an updated code snippet:
In addition to using CREATE TABLE #temp_table syntax, I've also updated the code to use QUOTENAME() function to properly escape the column names in the queries. This can help prevent SQL injection attacks and ensure that the code is more robust.