Get the schema name of the stored procedure of any database

Viewed 42

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.

1 Answers

You need to create a UNION ALL query which will select from every single database

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.

Related