[英]T-SQL row count for each table with a WHERE
I'm using SQL Server and have the below query to retrieve the RowCount of all tables that begin with 'IN%'. 我正在使用SQL Server,并具有以下查询来检索以'IN%'开头的所有表的RowCount。 This works fine. 这很好。
However, within each 'IN...' table there is a column called 'ErrorFlg' - this can be 0 or 1. 但是,在每个“ IN ...”表中都有一个名为“ ErrorFlg”的列-可以为0或1。
How do I modify the below to also include a new column called 'NoOfErrors' that will count where the 'ErrorFlg = 1' in each table? 如何修改以下内容,使其还包括一个名为“ 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
Ideal output: 理想输出:
TableName RowCnt NoOfErrors
--------------------------------
IN_123 100 50
IN_4566 500 2
IN_ABC 250 125
As per @Lamu's suggestion, The will create a table variable with your results and then create and execute dynamic statements... 根据@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.