应该这样做
SET NOCOUNT ON;
-- populate table
create table my_test_table
(
foo1 int,
foo2 int,
foo3 int,
foo4 int,
foo5 int
)
INSERT INTO my_test_table
select 1,2,3,4,5
INSERT INTO my_test_table
select 1,2,null,4,5
INSERT INTO my_test_table
select 1,2,3,4,null
INSERT INTO my_test_table
select 1,null,3,4,null
-- Actual query needed for question
declare @columns table
(
ident int identity(1,1),
column_name varchar(255)
)
INSERT INTO @columns (column_name)
SELECT c.[name]
FROM sys.columns c
INNER JOIN sys.objects o ON (c.object_id = o.object_id)
WHERE o.[name] = 'my_test_table'
ORDER BY c.column_id
declare @table_count int = (select COALESCE(count(ident),0) from @columns)
declare @counter int = 1
declare @column_name varchar(255)
declare @sql nvarchar(max) = ''
while (@table_count > 0 AND @counter <= @table_count)
BEGIN
select @column_name = column_name
from @columns
where ident = @counter
set @sql += ', count(' + @column_name + ') as [' + @column_name + '_total]'
set @counter += 1
END
exec('select count(*) as total' + @sql + ' from my_test_table')
确保将“my_test_table”的名称更改为表名。
结果
total | foo1_total |foo2_total |foo3_total |foo4_total |foo5_total
--------+-------------+--------------+-------------+-------------+-----------
4 | 4 | 3 | 3 | 4 | 2
如果列总数与总数(第一列)不匹配,则它有一些 NULL。
测试:http://rextester.com/AVB29103