我需要列出集合数据库中的所有表,并为每个表列出CHECKSUM_AGG(BINARY_CHECKSUM(*))
。
我知道我可以使用sp_tables
列出所有表格,但我怎样才能将CHECKSUM_AGG(BINARY_CHECKSUM(*))
用作最后一栏的额外列?
答案 0 :(得分:0)
这似乎有用,但我不知道它会占用大量数据库需要多长时间:
if object_id('tempdb..#Tables') is not null
drop table #Tables;
select row_number() over (order by (select null)) as RowNum
,t.table_catalog as TableQualifier
,t.table_schema as TableOwner
,t.table_name as TableName
,case t.table_type
when 'base table'
then 'table'
else t.table_type
end as TableType
,null as TableChecksum
into #Tables
from information_schema.tables t
where t.table_type <> 'view';
declare @RowNum int;
declare @TableName nvarchar(100);
declare @TableChecksum bigint;
declare @SQL nvarchar(max);
while (select count(1) from #Tables where TableChecksum is null) > 0
begin
select top 1 @RowNum = RowNum
,@TableName = TableName
,@SQL = 'select @TableChecksum = checksum_agg(binary_checksum(*)) from ' + @TableName
from #Tables
where TableChecksum is null;
exec sp_executesql @SQL
,N'@TableChecksum bigint output'
,@TableChecksum output;
update #Tables
set TableChecksum = @TableChecksum
where RowNum = @RowNum;
end;
select *
from #Tables;
if object_id('tempdb..#Tables') is not null
drop table #Tables;