SQL COUNT(column_name) 来自 table 所有列的名称

SQL COUNT(column_name) from table name for all columns

我有大约 1000 列。我们能否通过排除每个字段的空值来获取 table 中每一列的数字记录。 SQL 来自 table 名称查询的 COUNT(column_name) 排除空值。但是对 1000 列手动执行此操作是不可能的。如果有任何其他程序可以做到这一点,请告诉我。

这是一个动态示例 SQL:

/* Param var of the table to be queried */
DECLARE @Table VARCHAR(50) = 'Misc';

/* Build a list of column names to count */

DECLARE @sql VARCHAR(MAX) = ''; -- Important to initialize to an empty string.

SELECT @sql = @sql 
    + CASE WHEN LEN( @sql ) > 0 THEN ', ' ELSE '' END
    + CASE TYPE_NAME( system_type_id )
        WHEN 'text' THEN 'COUNT( CAST([' + [name] + '] AS varchar(1) ) ) AS [' + [name] + '_count]'
        ELSE 'COUNT( [' + [name] + '] ) AS [' + [name] + '_count]'
    END
FROM [sys].[columns] WHERE 
    [object_id] = OBJECT_ID ( @Table );

/* Complete and execute dynamic statement */

SET @sql = 'SELECT ' + @sql + ' FROM ' + @Table + ';';
EXEC( @sql );

Teradata 转换: https://www.jooq.org/translate/

declare Table varchar(50) default 'tblOrders';
declare sql varchar(32000) default '';
select ((@sql + case
  when length(@sql) > 0 then ', '
  else ''
end) + case TYPE_NAME(system_type_id)
  when 'text' then (('COUNT( CAST([' + "name" + '] AS varchar(1) ) ) AS [') + "name" + '_count]')
  else (('COUNT( [' + "name" + '] ) AS [') + "name" + '_count]')
end) @sql
from "sys"."columns"
where "object_id" = OBJECT_ID(@Table);
set sql = (('SELECT ' + @sql + ' FROM ') + @Table + ';');