仅返回具有存储过程的数据库名称

时间:2018-04-13 03:22:01

标签: sql-server stored-procedures

我在这里和其他论坛搜索了很多,但没找到我需要的东西。我的SQL Server上有97个数据库,但只有大约30个存储过程。我只需要选择具有存储过程的数据库的名称。我想我需要同时使用这两个查询。

SELECT name FROM sys.databases
SELECT name, type FROM dbo.sysobjects WHERE (type = 'P')

我想我需要与他们联系,但不确切知道如何。

非常感谢你的时间

2 个答案:

答案 0 :(得分:5)

这将使每个数据库中没有SP。

使用Dynamic SQL为每个数据库构建查询,然后使用exec()执行查询

declare @sql    nvarchar(max)

-- Create a temp table to store the result
create table #temp (db varchar(100), cnt int)

-- Generate the dynamic query for each of the database
select  @sql    = isnull(@sql, '')
                + 'insert into #temp '   -- added this line to insert result  into temp table
                + 'select db = ''' + name + ''', count(*) from ' + quotename(db.name) + '.dbo.sysobjects where type = ''P'';'
from    sys.databases db

-- Print out the dynamic query for your reference / verification
print   @sql
-- clear the temp table
delete  #temp   
-- execute the dynamic query
exec    (@sql)

-- retrieve the result from temp table
select  db
from    #temp
where   cnt > 0

您可以将结果插入临时表,然后从那里查询

答案 1 :(得分:3)

您可以使用sp_MSforeachdb循环所有dbs

DECLARE @command varchar(1000) 
SELECT @command = 'IF ''?'' NOT IN(''master'', ''model'', ''msdb'', ''tempdb'') BEGIN USE ? ; IF EXISTS (SELECT 1 FROM sysobjects WHERE xtype = ''P'' ) select DB_NAME() END'
EXEC sp_MSforeachdb @command 
相关问题