每个带有WHERE的表的T-SQL行计数

时间:2019-01-09 17:00:58

标签: sql sql-server

我正在使用SQL Server,并具有以下查询来检索以'IN%'开头的所有表的RowCount。效果很好。

但是,在每个“ IN ...”表中都有一个名为“ ErrorFlg”的列-可以为0或1。

如何修改下面的内容以包含一个名为“ NoOfErrors”的新列,该列将计算每个表中“ ErrorFlg = 1”的位置?

SELECT        
    ta.name AS TableName, 
    SUM(pa.rows) AS RowCnt
FROM
    sys.tables AS ta 
INNER JOIN
    sys.partitions AS pa ON pa.object_id = ta.object_id 
INNER JOIN
    sys.schemas AS sc ON ta.schema_id = sc.schema_id
WHERE
    (ta.is_ms_shipped = 0) AND (pa.index_id IN (1, 0)) 
    AND (ta.name LIKE 'IN_%')
GROUP BY 
    sc.name, ta.name
ORDER BY 
    TableName, RowCnt DESC

理想的输出:

TableName    RowCnt   NoOfErrors
--------------------------------
IN_123        100       50
IN_4566       500        2
IN_ABC        250      125

1 个答案:

答案 0 :(得分:0)

根据@Lamu的建议,The将使用您的结果创建一个表变量,然后创建并执行动态语句...

Declare @Tbl Table 
(
TableName VarChar(50),
RowCnt Int
)

Insert Into @Tbl
   SELECT    
     ta.name AS TableName, 
     SUM(pa.rows) AS RowCnt 
   FROM
     sys.tables AS ta 
   INNER JOIN 
     sys.partitions AS pa ON pa.object_id = ta.object_id 
   INNER JOIN
     sys.schemas AS sc ON ta.schema_id = sc.schema_id
   WHERE
     (ta.is_ms_shipped = 0) AND (pa.index_id IN (1, 0)) 
     AND (ta.name LIKE 'IN_%')
   GROUP BY 
     sc.name, ta.name
   ORDER BY 
     TableName, RowCnt DESC


Declare @tblname VarChar(50)
Declare @rowcnt VarChar(10)
Declare @vsql VarChar(Max) = NULL

Declare c Cursor For Select TableName,RowCnt From @Tbl
Open c
Fetch Next From c Into @tblname, @rowcnt

WHILE @@FETCH_STATUS = 0
    BEGIN
       Set @vsql = 'Select ''' + @tblname +''' As Tbl,''' + @rowcnt + ''' As RowCnt, Count(*) As NoOfErrors From ' + @tblname + ' Where ErrorFlg = 1'
       Exec(@vsql)
       Set @vsql = NULL
       Fetch Next From c Into @tblname, @rowcnt
    END