if exists (select * from tempdb..sysobjects where name ='##T')
drop table ##T
create table ##T (name varchar(128),keys varchar(1000),tab varchar(100))
exec sp_MSforeachtable '
insert ##T(name,keys)
exec sp_helpstats ''?''
update ##T set tab=''?''
where tab is null
'
select
'
begin try
if object_id('''+tab+''') is not null and
exists(select 1 from sys.stats
where name ='''+name+''' and object_id = object_id('''+tab+'''))
drop STATISTICS '+tab+'.'+quotename(name)+'
end try
begin catch
print ERROR_MESSAGE()
end catch
' del,
'
if object_id('''+tab+''') is not null and
not exists(select 1 from sys.stats
where name ='''+name+''' and object_id = object_id('''+tab+'''))
create STATISTICS '+quotename(name)+' on '+tab+'('+keys+')
' ad
from ##T a
--WHERE exists(select * from [master].[dbo].[UnionALL]
--where quotename(sch)+'.'+quotename(tbl)=a.tab and a.keys like '%'+col+'%')
--select * from ##T
drop table ##T