从SQL Server 2008中的所有数据库获取所有存储过程

时间:2013-03-30 23:57:47

标签: sql-server-2008 stored-procedures

有人可以建议在所有数据库中检索所有存储过程的列表及其架构名称的方法吗?感谢您的投入!

4 个答案:

答案 0 :(得分:10)

CREATE TABLE #x(db SYSNAME, s SYSNAME, p SYSNAME);

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'INSERT #x SELECT ''' + name + ''',s.name, p.name
  FROM ' + QUOTENAME(name) + '.sys.schemas AS s
  INNER JOIN ' + QUOTENAME(name) + '.sys.procedures AS p
  ON p.schema_id = s.schema_id;
' FROM sys.databases WHERE database_id > 4

EXEC sp_executesql @sql;

SELECT db,s,p FROM #x ORDER BY db,s,p;

DROP TABLE #x;

答案 1 :(得分:2)

对于所有数据库,搜索用户定义的存储过程,视图,函数和表值函数,以下内容可能有所帮助(基于上面的Habo):

declare @Sprocs as Table (DBName VarChar(64), SchemaName varchar (128), 
    StoredProcName VarChar(128), 
    type varchar(10), type_desc varchar(128), 
    create_date datetime, modify_date datetime, is_MS_Shipped int)
insert into @Sprocs
    execute sp_MSforeachdb N'use ?; select ''?'', 
        s.name as SchemaName, o.name as StoredProcName, 
        type, type_desc, create_date, modify_date, is_MS_Shipped
        from sys.all_objects as o inner join sys.schemas as s 
            on s.schema_id = o.schema_id 
        where o.type in (''P'', ''V'', ''PC'', ''FN'', ''TF'')
            and is_ms_shipped = 0'

select * from @Sprocs
where DBName not in ('master', 'tempdb', 'model', 'msdb', 'dba') 
order by DBName, SchemaName, type, StoredProcName

添加'U'以获取用户生成的表格。

答案 2 :(得分:1)

对于单个数据库:

select s.name + '.' + p.name as sproc_name_with_schema
  from sys.procedures as p inner join
    sys.schemas as s on s.schema_id = p.schema_id

您是否需要所有数据库?你的问题有点不清楚。

declare @Sprocs as Table ( DBName VarChar(64), SprocName VarChar(128) )
insert into @Sprocs
  execute sp_MSforeachdb N'use ?; select ''?'', s.name + ''.'' + o.name from sys.all_objects as o inner join sys.schemas as s on s.schema_id = o.schema_id where o.type = ''P'''
select * from @Sprocs

答案 3 :(得分:1)

没有临时表和插入的第一个答案的替代方法:

declare @sql varchar(max) = '';
select 
    @sql += ' ' +
    'union all ' +
    'select ''' +
        dat.name + ''' as bas, b.name as sch, a.name as pro ' +
    'from ' +
        '[' + dat.name + '].[sys].procedures as a ' +
        'inner join [' + dat.name + '].[sys].schemas as b on a.schema_id = b.schema_id'
from sys.databases as dat;
set @sql = RIGHT(@sql, LEN(@sql) - 11);
exec(@sql);
print @sql;