Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all stored procedures with schema name

Can anyone advise on a way to list all stored procedures along with their schema names in a database? Thanks!

like image 675
daniness Avatar asked Sep 27 '12 13:09

daniness


People also ask

How do I find a list of Stored Procedures in a database?

View the list of stored procedure in a database using a query. To view the list of the stored procedure, you can query the information_schema. routines table. It contains the list of the stored procedure and stored functions created on the database.

How do I list schemas in SQL?

You can get a list of the schemas using an SSMS or T-SQL query. To do this in SSMS, you would connect to the SQL instance, expand the SQL database and view the schemas under the security folder. Alternatively, you could use the sys. schemas to get a list of database schemas and their respective owners.


1 Answers

SELECT [schema] = OBJECT_SCHEMA_NAME([object_id]),
  name
FROM sys.procedures;

or

SELECT [schema] = SCHEMA_NAME([schema_id]),
  name
FROM sys.procedures;

For a specific database, you can just change the context to that database first, or change Marc's query slightly (my queries are no good in this case because they rely on functions that are context-sensitive):

SELECT 
    SchemaName = s.name,
    ProcedureName = pr.name 
FROM 
    databasename.sys.procedures pr
INNER JOIN 
    databasename.sys.schemas s ON pr.schema_id = s.schema_id;

If you want to do this for all databases:

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

SELECT @sql += N'
  UNION ALL SELECT db = N''' + name + ''', 
    s.name COLLATE Latin1_General_CI_AI,
    o.name COLLATE Latin1_General_CI_AI
  FROM ' + QUOTENAME(name) + '.sys.procedures AS o
  INNER JOIN ' + QUOTENAME(name) + '.sys.schemas AS s
  ON o.[schema_id] = s.[schema_id]'
FROM sys.databases
-- WHERE ... -- probably don't need system databases at least

SELECT @sql = STUFF(@sql, 1, 18, '') 
  -- you may have to adjust  ^^ 18 due to copy/paste, cr/lf, tabs etc 
  + ' ORDER BY by db, s.name, o.name';

EXEC sp_executesql @sql;

The collate clauses are necessary in case you have databases with different collations.

like image 66
Aaron Bertrand Avatar answered Sep 28 '22 08:09

Aaron Bertrand