Есть несколько способов получить детали объекта, которые вы ищете во всех базах данных.Ниже я включил два решения: одно с использованием метода cursor
, которое было предпринято в вопросе, и другое, которое проще, чем хранимая процедура sp_msforeachdb
.
Метод курсора:
declare @db_nm varchar(250)
, @sql varchar(1000)
DECLARE @results TABLE (
[database_name] sysname,
[object_name] sysname,
[schema_name] sysname,
[Object_Description] sysname
);
declare db cursor local
fast_forward for
select db.name
from master.sys.databases as db
where db.name not in ('master', 'tempdb', 'model', 'msdb') --system db you're probably not looking for info in
open db
fetch next from db into @db_nm;
while @@fetch_status = 0
begin
set @sql =
'select ''' + @db_nm + ''' AS [database_name]
, s.name + ''.'' + o.name as [object_name]
, type as [schema_name]
, type_desc as [Object_Description]
FROM [' + @db_nm + '].sys.objects as o
INNER JOIN [' + @db_nm + '].sys.schemas as s ON o.schema_id = s.schema_id
where type in (''p'', ''pc'', -- stored procs
''v'', -- views
''tf'', ''if'', ''ft'', -- table-valued functions
''fn'', ''fs'', -- scalar-valued functions
''af'' -- aggregate functions
)
'
insert into @results
exec (@sql)
fetch next from db into @db_nm;
end
close db
deallocate db
select *
from @results
sp_msforeachdb Метод:
Этот метод сопровождается предупреждением о том, что процедура не документирована.
declare @sql varchar(1000) =
'
if ''?'' not in (''master'', ''tempdb'', ''model'', ''msdb'') --system db youre probably not looking for info in
begin
select ''?'' AS [database_name]
, s.name + ''.'' + o.name as [object_name]
, type as [schema_name]
, type_desc as [Object_Description]
FROM [?].sys.objects as o
INNER JOIN [?].sys.schemas as s ON o.schema_id = s.schema_id
where type in (''p'', ''pc'', -- stored procs
''v'', -- views
''tf'', ''if'', ''ft'', -- table-valued functions
''fn'', ''fs'', -- scalar-valued functions
''af'' -- aggregate functions
)
end
'
DECLARE @results TABLE (
[database_name] sysname,
[object_name] sysname,
[schema_name] sysname,
[Object_Description] sysname
);
insert into @results
exec master.dbo.sp_msforeachdb @sql
select *
from @results