如何计算多个表

时间:2015-02-19 13:48:18

标签: sql sql-server

我正在使用此代码从所有具有72个表的表中获取ABC计数

如果我使用

declare @SQL nvarchar(max)
declare @Countt bigint

SELECT @SQL = STUFF(( SELECT ' ; SELECT COUNT(ABC) FROM   ' + INFORMATION_SCHEMA.TABLES.TABLE_NAME 

FROM INFORMATION_SCHEMA.TABLES LEFT OUTER JOIN  INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME where INFORMATION_SCHEMA.TABLES.TABLE_TYPE =N'BASE TABLE' AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME =N'ABC'
FOR XML PATH('')),1,2,'')

SET @SQL = @SQL

PRINT @SQL

EXECUTE (@SQL) 

但是我一个接一个得到72个结果,但我只想得到所有72个结果的总和,例如如果ABC在4个表中有10行所以应该返回40请告诉我哪里错了或者其他更好的方式

4 个答案:

答案 0 :(得分:2)

declare @SQL nvarchar(max)
declare @Countt bigint

SELECT @SQL = STUFF(( SELECT ' UNION ALL SELECT COUNT(ABC) AS noCount FROM   ' + INFORMATION_SCHEMA.TABLES.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES LEFT OUTER JOIN  INFORMATION_SCHEMA.COLUMNS ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME where INFORMATION_SCHEMA.TABLES.TABLE_TYPE =N'BASE TABLE' AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME =N'ABC' FOR XML PATH('')),1,10,'')

SET @SQL = 'SELECT COUNT(*) FROM  (' + @SQL + ')A'

PRINT @SQL

EXECUTE (@SQL) 

答案 1 :(得分:2)

每个人都是对的,只需要添加架构,如果有不同的架构:

declare @SQL nvarchar(max)
declare @Countt bigint



SELECT @SQL = STUFF(( 

SELECT DISTINCT ' UNION ALL SELECT COUNT(ABC) AS CountAmount FROM   ' + INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA + '.' + INFORMATION_SCHEMA.TABLES.TABLE_NAME AS [text()]
FROM INFORMATION_SCHEMA.TABLES 
LEFT OUTER JOIN  INFORMATION_SCHEMA.COLUMNS 
    ON INFORMATION_SCHEMA.TABLES.TABLE_NAME = INFORMATION_SCHEMA.COLUMNS.TABLE_NAME 
WHERE INFORMATION_SCHEMA.TABLES.TABLE_TYPE =N'BASE TABLE' 
    AND INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME =N'ABC'
FOR XML PATH('')),1,11,'')

SET @SQL = 'SELECT SUM( CountAmount ) AS TotalSum FROM (' + @SQL + ' ) AS T '

PRINT @SQL

EXECUTE (@SQL) 

答案 2 :(得分:-1)

使用游标并逐个迭代每个表。生成动态sql字符串时,将结果选择为变量,如下所示:

    select @TableCount = Count(ABC) From SomeTable
    set @TotalCount = @Totalcount + @TableCount

答案 3 :(得分:-1)

您需要使用聚合函数并对结果进行分组。因此,如果我正确读取您的sql,请按INFORMATION_SCHEMA.TABLES.TABLE_NAME分组