我正在尝试修改此查询,以便为数据库中的每个表提供行计数,其中表包含“Archive”列,总行数以及“Archive = 1”的行数。我已经完成了第一部分,但我的第二部分是大脑放屁。
SELECT sc.name +'.'+ ta.name TableName,SUM(pa.rows) RowCnt
FROM sys.tables ta
INNER JOIN sys.partitions pa ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
AND OBJECT_NAME(pa.object_id) IN
(
--Criteria 1
SELECT iq.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS iq
WHERE COLUMN_NAME LIKE '%Archive%'
)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
提前感谢您的任何帮助或建议。
答案 0 :(得分:1)
这有点令人讨厌,但希望这会奏效:
create table #result
(
schemaName sysname, tableName sysname, recordCount bigint, archiveCount bigint, sqlCommand nvarchar(max)
)
alter table #result add primary key clustered (schemaName, tableName)
insert #result (schemaName, tableName, recordCount, archiveCount, sqlCommand)
SELECT sc.name, ta.name, 0, 0, 'update r set sqlCommand=null, recordCount=cnt, archiveCount=arch from #result r inner join
(select ' + quotename(sc.name,'''') + ' schemaName, ' + quotename(ta.name,'''') + ' tableName, count(1) cnt, count(case' +
(SELECT
' when ' + QUOTENAME(c2.name) + ' = 1 then 1'
FROM sys.columns c2
WHERE c2.object_id = ta.object_id
and c2.name like '%Archive%'
and c2.system_type_id = 56 --int
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
+ ' else null end) arch from ' + QUOTENAME(sc.name) + '.' + QUOTENAME(ta.name) + ') x on x.schemaName=r.schemaName and x.tableName=r.tableName'
FROM sys.tables ta
INNER JOIN sys.schemas sc
ON sc.schema_id = ta.schema_id
INNER JOIN sys.columns c
ON c.object_id = ta.object_id
WHERE ta.is_ms_shipped = 0
and c.name like '%Archive%'
and c.system_type_id = 56 --select name, system_type_id from sys.types where name='int'
GROUP BY sc.name,ta.object_id,ta.name
declare @sql nvarchar(max)
select @sql = sqlCommand from #result where sqlCommand is not null
while @sql is not null
begin
print @sql
exec(@sql)
set @sql = null
select @sql = sqlCommand from #result where sqlCommand is not null
end
select * from #result