34

I am exploring a legacy database system and have very little knowledge of its internals. I would like to find all the stored procedures that invoke another stored procedure A.

How best to do this?

Can I write something like this pseudocode:

select name from AllStoredProcedures as Asp where Asp.TextualContent contains 'A'

Asp.TextualContent means the actual SQL contained in the SP.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331

4 Answers4

67
SELECT OBJECT_NAME(object_id),
       definition
FROM sys.sql_modules
WHERE objectproperty(object_id,'IsProcedure') = 1
  AND definition    like '%Foo%' 
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
7

For SQL Server 2005/2008:

SELECT  s.name SchemaName
        ,o.name RoutineName
        ,o.[type] RoutineType
        ,procs.*
FROM    sys.sql_modules procs
INNER JOIN sys.objects o ON procs.object_id = o.object_id 
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE   procs.[definition] LIKE '%A%'
--AND       o.[type] = 'P' --'P' for stored procedures
Bogdan Sahlean
  • 19,233
  • 3
  • 42
  • 57
3

This query will retrieve the textual definition of stored procedures and filter using a simple wildcard.

For 2000 (untested, but IIRC it's the right table):

select p.[type]
      ,p.[name]
      ,c.[text]
  from sysobjects p
  join syscomments c
    on p.object_id = c.id
 where p.[type] = 'P'
   and c.[text] like '%foo%'

For 2005:

select p.[type]
      ,p.[name]
      ,c.[text]
  from sys.objects p
  join sys.syscomments c
    on p.object_id = c.id
 where p.[type] = 'P'
   and c.[text] like '%foo%'

For 2005 and 2008+

select p.[type]
      ,p.[name]
      ,c.[definition]
  from sys.objects p
  join sys.sql_modules c
    on p.object_id = c.object_id
 where p.[type] = 'P'
   and c.[definition] like '%foo%'
ConcernedOfTunbridgeWells
  • 64,444
  • 15
  • 143
  • 197
  • 1
    `sys.syscomments` shouldn't be used for this as it splits long definitions up into 4,000 character chunks so you can miss matches that cross chunk boundaries. – Martin Smith Oct 07 '11 at 11:21
1

Try This only one statement can solve your problem..

--note this does not show /r/n, it comes out as one long line
SELECT OBJECT_DEFINITION(OBJECT_ID(N'dbo.myStoredProc'))

or

DECLARE @objname nvarchar(max); -- note this truncates
SELECT @objname= OBJECT_DEFINITION(OBJECT_ID(N'dbo.myStoredProc'))
print @objname
OzBob
  • 4,227
  • 1
  • 39
  • 48
Apps Tawale
  • 665
  • 7
  • 7
  • OP asked for support of 'like', but if you need to get just one SP use: PRINT OBJECT_DEFINITION(OBJECT_ID(N'dbo.myStoredProc')) – OzBob Mar 15 '22 at 04:09