我试图在一台服务器上的所有数据库中找到重复的对象名称。有没有找到所有重复?我使用游标循环遍历数据库,我想检查一个对象是否显示多个,名为duplicates的列将填充是或否。
答案 0 :(得分:2)
使用msforeachdb内置函数/ proc,然后将这些结果插入到临时表中。然后查询临时表并进行具有count(1)>的groupby。 1
create table #tables (db varchar(100) not null, name varchar(100) not null)
exec sp_msforeachdb 'use [?] insert into #tables select distinct db_name(), [name] from sys.objects where [type] = ''U'''
select name, count(1) from #tables group by name having count(1) > 1 order by 2 desc
drop table #tables
这并不准确,但你明白了。我一直在调整,直到我知道它是对的。
这是光标版本:
set nocount on
SELECT name
into #dbs
FROM sys.databases
declare dbCursor cursor local forward_only for
select name from #dbs
declare @db varchar(100)
create table #tables (db varchar(100) not null, name varchar(100) not null)
open dbCursor
fetch next from dbCursor into @db
while (@@fetch_status = 0) begin
begin try
exec ('use ' + @db + ' insert into #tables select distinct db_name(), [name] from sys.objects where [type] = ''U''')
print 'got ' + @@rowcount + ' from db ' + @db
end try
begin catch
print 'couldn''t retrieve data from database ' + @db
end catch
fetch next from dbCursor into @db
end
close dbCursor
deallocate dbCursor
select name, count(1) from #tables group by name having count(1) > 1 order by 2 desc
drop table #tables
drop table #dbs