이 약간 불쾌한, 그러나 희망이 작동합니다 :
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
스틱 당신의 수를 내부 case 문. . . 그러나 모든 테이블을 쿼리하는 경우 다른 테이블 스키마를 수용하기 위해 일부 동적 SQL을 수행해야합니다. – JohnLBevan
@ JohnLBevan 그게 작동하지만 구문이나 스키마 또는 테이블을 사용하여 잘 모르겠습니다? 대. (스키마) .column? –
True - 아카이브 열을 특징으로하는 모든 테이블의 모든 행을 보지 않고 아카이브 열이 하나만 있으면 좋겠다고 질문을 잘못 읽었습니다. DynamicSql 제안을 포함하도록 원래 코멘트를 수정했으며 아래에 솔루션을 제공했습니다. 희망이 도움이됩니다. – JohnLBevan