More code...
So you're about to change a column in the enormous database you inherited (or got stuck with,) and you haven't the slightest idea which of the hundreds of stored procedures and triggers you're about to break. Will you create a bug that bankrupts the company and requires you to blame some perfectly innocent coworker to keep from getting fired?
Microsoft SQL Server doesn't have a search function, but this procedure adds one for you. It could be improved to show the offending line(s), but it's still very useful to be able to pinpoint specific procedures, functions, and triggers that contain the search text.
This procedure works on SQL2000 and SQL2005.
Bonus fact: The 'sp_' prefix tells SQL server to look for a stored procedure in the master database first, and look in your local database second. This of course is why system procedures start with 'sp_'. It is also why you should never use this prefix for your procedures - SQL will go looking in the master database first, which of course is a waste of time.
CREATE PROC sp_search_code
(
@SearchStr varchar(100),
@RowsReturned int = NULL OUT
)
AS
/******************************************************************************
Purpose: To search the stored procedure, UDF, trigger code for a given keyword.
Install this in the master database of the server, then run from the
database you wish to search.
Written by: Narayana Vyas Kondreddi
http://vyaskn.tripod.com
Added to SQL2000 by Jim Rogers
******************************************************************************/
BEGIN
SET NOCOUNT ON
SELECT DISTINCT USER_NAME(o.uid) + '.' + OBJECT_NAME(c.id) AS 'Object name',
CASE
WHEN OBJECTPROPERTY(c.id, 'IsReplProc') = 1
THEN 'Replication stored procedure'
WHEN OBJECTPROPERTY(c.id, 'IsExtendedProc') = 1
THEN 'Extended stored procedure'
WHEN OBJECTPROPERTY(c.id, 'IsProcedure') = 1
THEN 'Stored Procedure'
WHEN OBJECTPROPERTY(c.id, 'IsTrigger') = 1
THEN 'Trigger'
WHEN OBJECTPROPERTY(c.id, 'IsTableFunction') = 1
THEN 'Table-valued function'
WHEN OBJECTPROPERTY(c.id, 'IsScalarFunction') = 1
THEN 'Scalar-valued function'
WHEN OBJECTPROPERTY(c.id, 'IsInlineFunction') = 1
THEN 'Inline function'
END AS 'Object type',
LEN(c.text) AS Length
INTO #temp
FROM syscomments c
LEFT OUTER JOIN syscomments c1 ON c.id = c1.id AND c1.colid = c.colid + 1
JOIN sysobjects o ON c.id = o.id
WHERE c.text + CASE WHEN c1.text IS NULL THEN '' ELSE c1.text END
LIKE '%' + @SearchStr + '%' AND
c.encrypted = 0 AND
(
OBJECTPROPERTY(c.id, 'IsReplProc') = 1 OR
OBJECTPROPERTY(c.id, 'IsExtendedProc') = 1 OR
OBJECTPROPERTY(c.id, 'IsProcedure') = 1 OR
OBJECTPROPERTY(c.id, 'IsTrigger') = 1 OR
OBJECTPROPERTY(c.id, 'IsTableFunction') = 1 OR
OBJECTPROPERTY(c.id, 'IsScalarFunction') = 1 OR
OBJECTPROPERTY(c.id, 'IsInlineFunction') = 1
)
ORDER BY 'Object type', 'Object name'
SET @RowsReturned = @@ROWCOUNT
END
SELECT * FROM #temp
DROP TABLE #temp
GO