这有点讨厌,但希望这会奏效:
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