navigation
 Wednesday, February 14, 2007

How do you find if a table is referenced in a stored proc?  That can be quite the Easter egg hunt without some sort of tool.  The following SQL uses the syscomments table (contains the stored proc text) and joins to the sysobjects table to determine which syscomment records belong to stored procs.  CHARINDEX returns the starting position of an expression in a character string, so the fact that it returns greater than zero signals a hit.

DECLARE @SEARCHSTRING VARCHAR(255)

SELECT @SEARCHSTRING = 'MyTable'

SELECT DISTINCT sysobjects.name
FROM sysobjects,syscomments
WHERE sysobjects.id = syscomments.id
-- look for stored procs only
AND sysobjects.type = 'P'
AND sysobjects.category = 0
-- what you are looking for, what you're looking in
AND CHARINDEX(@SEARCHSTRING,syscomments.text)>0

This is a reduced version taken from an example at:

http://wiki.ittoolbox.com/index.php/HOWTO:Search_the_text_of_triggers_and_stored_procedures

Another handy related query from Adam Anderson's toolbox of SQL techniques finds references to column names.  This one lists the table names where tables contain "Created" and "Modified" users and dates:

select distinct so.name
from sysobjects so
where exists (
select *
from syscolumns sc
where sc.id = so.id
and sc.name in ( 'CreatedBy', 'CreatedOn', 'ModifiedBy', 'ModifiedOn' )
)

More info about CHARINDEX at http://msdn2.microsoft.com/en-us/library/ms186323.aspx.

Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, i, strike, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview