简体   繁体   English

获取任意数据库的存储过程的模式名

[英]Get the schema name of the stored procedure of any database

Currently, I have this database query which works fine if it runs under the database to which the stored procedure belongs目前,我有这个数据库查询,如果它在存储过程所属的数据库下运行,它可以正常工作

SELECT sys.objects.name, sys.schemas.name AS schema_name
FROM sys.objects 
INNER JOIN sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id 
WHERE sys.objects.name = 'usp_gallery_delete'

What I am trying to do is, irrespective of any database I am in, if I execute the passed stored procedure name, I should be able to get the schema name of that stored procedure and also should be able to get the definition of that stored procedure.我想做的是,无论我在哪个数据库中,如果我执行传递的存储过程名称,我应该能够获取该存储过程的模式名称,并且还应该能够获取该存储过程的定义程序。

You need to create a UNION ALL query which will select from every single database您需要创建一个UNION ALL查询,它将 select 从每个数据库

DECLARE @sql nvarchar(max);

SELECT @sql = STRING_AGG(CAST('
SELECT
  o.name COLLATE Latin1_General_CI_AS AS name,
  s.name COLLATE Latin1_General_CI_AS AS schema_name
FROM ' + QUOTENAME(d.name) + '.sys.objects o
INNER JOIN ' + QUOTENAME(d.name) + '.sys.schemas s ON o.schema_id = s.schema_id 
WHERE o.name = ''usp_gallery_delete''
'  AS nvarchar(max)), '
UNION ALL
'  )

FROM sys.databases d
WHERE d.database_id > 4;  -- not system DB


EXEC sp_executesql @sql;

Note the use of QUOTENAME to quote the injected database name, and note the use of short meaningful table aliases.请注意使用QUOTENAME引用注入的数据库名称,并注意使用简短的有意义的表别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM