Finding a stored procedure - sql

How can we find a particular stored procedure. I need to find a stored procedure which I don't know is in which database. Can somebody please, help with a script.
Thanks

One way by using the ANSI information_schema.routines view, change ProcNameHere to the name you want
select * from information_schema.routines
where routine_type = 'PROCEDURE'
and specific_name = 'ProcNameHere'

Which database server? With MS SQL Server, you can use sp_help 'procname'.

If it is Sql Server 2005 you can use
SELECT * FROM Sys.Objects where Name = 'YOUR_NAME_HERE' AND type = 'P'
It will tell you if the procedure is in a particular database.

Which SQL? SQL 2k/2k5/2k8 has management studio which lets you browse. Expand Databases/Database/Programmability/Stored Proceudres

Replace text to search for with your string and this will search all databases on your server.
exec sp_MSforeachdb 'SELECT db=''?'', [type], [name], [text] FROM [?]..sysobjects a inner join [?]..syscomments b on a.id = b.id where text like ''%Text to search for%'' order by [name], [number]', '?'

Related

How to avoid showing result-window if there are no results to show?

I have a script which searches through all the available databases (those I have access to) for a specific text in a procedure.
In my server, there are many databases (in my case about 150 databases), meaning that I get shown the results for all databases eventhough there are no results for most of them (about 90%).
Is there any way to avoid getting these empty result-queries?
You can use below code to check whether stored procedure contains a text in each database. If there are stored procedures in a database only, you will have resultset.
CREATE TABLE ##DatabasesContainingSP(dbname sysname, SPName SYSNAME);
EXECUTE master.sys.sp_MSforeachdb 'USE [?];
INSERT INTO ##DatabasesContainingSP
SELECT DISTINCT
db_name() as dbname, o.name AS Object_Name
FROM sys.sql_modules m
INNER JOIN
sys.objects o
ON m.object_id = o.object_id
WHERE m.definition Like ''%ABC%'';
'
IF EXISTS(SELECT * FROM ##DatabasesContainingSP )
begin
SELECT * FROM ##DatabasesContainingSP
end
GO
IF OBJECT_ID('tempdb..##DatabasesContainingSP' , 'U') IS NOT NULL
drop TABLE ##DatabasesContainingSP;
Thank you for the quick responses.
I managed to solve it by creating a table and adding insert into this table in the beginning of my generated and concatenated code, which solved the problem since when reading the table in the end, it only shows the inserted results.
With kind regards,
Alexander

Find and replace content in stored procedures ms sql server

I want to rename tables and views which are used in stored procedures. Is there any way to find and replace table names in stored procedures, maybe there is tool for ms sql server (i'm using ms sql server 2012).
SQL Server might not allow you to directly UPDATE the object definitions (Views and Stored Proceduress in your case) present in the System catalogs even after setting the 'Allow Updates' option to 1.
The following code will generate the required ALTER Script and you can run them manually after reviewing the definitions ([ModifiedDefinition] )or u can loop through each value of [ModifiedDefinition] and run it using sp_executesql.
SELECT
b.Name AS [ObjectName],
CASE WHEN b.type ='p' THEN 'Stored Procedure'
WHEN b.type ='v' THEN 'View'
ELSE b.TYPE
END AS [ObjectType]
,a.definition AS [Definition]
,Replace ((REPLACE(definition,'OLD Value','New Value')),'Create','ALTER') AS [ModifiedDefinition]
FROM sys.sql_modules a
JOIN
( select type, name,object_id
from sys.objects
where type in (
'p' -- procedures
,'v'--views
)
and is_ms_shipped = 0
)b
ON a.object_id=b.object_id
And as always, be careful with production data and take backups before performing bulk changes on object definitions!!
You can use DBvisualizer .. it pretty much works with all databases and with ms sql too, you can do all you mentioned by using this.
I answered this on another topic (https://stackoverflow.com/a/67728039/11165834) , I do it using the following script:
DECLARE #queryDef NVARCHAR(max)
WHILE EXISTS (
SELECT 1
FROM sys.sql_modules sm
JOIN sys.objects o ON sm.object_id = o.object_id
WHERE sm.definition LIKE '%TEXT_TO_REPLACE%'
AND o.type = 'V'
)
BEGIN
-- TO ALTER THE VIEW AUTOMATICALLY
SET #queryDef = ( SELECT TOP 1 Replace (Replace (sm.definition, 'CREATE VIEW', 'ALTER VIEW'),
'TEXT_TO_REPLACE',
'NEW_TEXT')
FROM sys.sql_modules sm
JOIN sys.objects o ON sm.object_id = o.object_id
WHERE sm.definition LIKE '%TEXT_TO_REPLACE%'
AND o.type = 'V')
EXEC (#queryDef)
END
I use it to replace procedures/views when I restore a backup from production into tests databases.
As #S.A said, be verry careful because is not a verry safe way.
Change the "o.type" and "Replace (sm.definition, 'CREATE VIEW', 'ALTER VIEW'" accordingly to your need

SQL code to open a stored procedure and read it in SQL Server

I am using an interface that only allows me to use SQL commands. The database is SQL Server. Right now I need to open a stored procedure and read what is inside of it. What is the SQL command to open a stored procedure for reading? Thank you.
SELECT definition
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('YourSchemaName.YourProcedureName')
sp_helptext 'dbo.myStoredProc'
SELECT OBJECT_DEFINITION(OBJECT_ID('dbo.myStoredProc'))
Note: subject to Metadata Visibility and VIEW DEFINITION rights
SELECT TEXT
FROM syscomments
WHERE id = (SELECT id FROM sysobjects WHERE name = '<NAME>')
ORDER BY colid

How can I get all the database names in a sql server instance using tsql?

How can I get all the database names in a sql server instance using tsql?
SELECT * FROM sys.databases
----SQL SERVER 2005 System Procedures
EXEC sp_databases
EXEC sp_helpdb
----SQL 2000 Method still works in SQL Server 2005
SELECT name
FROM sys.databases
SELECT name
FROM sys.sysdatabases
----SQL SERVER Un-Documented Procedure
EXEC sp_msForEachDB 'PRINT ''?'''
to know more about database : http://blog.sqlauthority.com/2007/05/12/sql-server-2005-list-all-the-database/
this should work on pretty much any version of sql server
USE master;
SELECT NAME FROM sysdatabases;
[edit : it could be SELECT NAME FROM sys.databases too, microsoft's website says both and i'm not on my windows box to test, sorry!]
you could also use (sql 2005 only)
USE master;
EXEC sp_databases;
And for practical use added couple of common filters:
select database_id, [name] database_name
from master.sys.databases
WHERE state <> 6 -- skip offline
AND database_id > 4 -- skip system dbs
AND HAS_DBACCESS([name]) = 1 -- with User Access
SQL 2000
use master
select name from sysdatabases
or
(no need for use master, includes database_size)
exec sp_databases

Stored procedures and the tables used by them

Is there a way to know what are the tables used by one stored procedure by doing an SQL query?
Best regards, and thanks for the help.
P.S.: I'm using SQL Server 2005.
This article on TechRepublic
Finding dependencies in SQL Server 2005
describes a way to do that:
This tutorial will show how you can
write a procedure that will look up
all of the objects that are dependent
upon other objects.
Here is the code to create the system stored procedure for finding object dependencies:
USE master
GO
CREATE PROCEDURE sp_FindDependencies
(
#ObjectName SYSNAME,
#ObjectType VARCHAR(5) = NULL
)
AS
BEGIN
DECLARE #ObjectID AS BIGINT
SELECT TOP(1) #ObjectID = object_id
FROM sys.objects
WHERE name = #ObjectName
AND type = ISNULL(#ObjectType, type)
SET NOCOUNT ON ;
WITH DependentObjectCTE (DependentObjectID, DependentObjectName, ReferencedObjectName, ReferencedObjectID)
AS
(
SELECT DISTINCT
sd.object_id,
OBJECT_NAME(sd.object_id),
ReferencedObject = OBJECT_NAME(sd.referenced_major_id),
ReferencedObjectID = sd.referenced_major_id
FROM
sys.sql_dependencies sd
JOIN sys.objects so ON sd.referenced_major_id = so.object_id
WHERE
sd.referenced_major_id = #ObjectID
UNION ALL
SELECT
sd.object_id,
OBJECT_NAME(sd.object_id),
OBJECT_NAME(referenced_major_id),
object_id
FROM
sys.sql_dependencies sd
JOIN DependentObjectCTE do ON sd.referenced_major_id = do.DependentObjectID
WHERE
sd.referenced_major_id <> sd.object_id
)
SELECT DISTINCT
DependentObjectName
FROM
DependentObjectCTE c
END
This procedure uses a Common Table
Expression (CTE) with recursion to
walk down the dependency chain to get
to all of the objects that are
dependent on the object passed into
the procedure. The main source of data
comes from the system view
sys.sql_dependencies, which contains
dependency information for all of your
objects in the database.
Try sp_depends, although you should probably recompile the stored procedure to update the statistics in the database.
Look up sp_depends system stored proc.
I think that as long as the stored procedure and the tables are all in the same database then you can right click on the procedure in SSMS and click "View Dependencies". I don't know the query behind the dialog though...
As others indicated you can use the Dependancies stored procedures; however, in my experience and this was back on SQL Server 2000, the depandancies were not always reliable. In some cases they weren't being updated. You can always go to the sysComments table assuming your schema is not encrypted.
declare #crlfSearch varchar(max),#objectSearch varchar(max),#escapeSearch varchar(max)
set #crlfSearch=('%bid' + char(13)+'%')
set #objectSearch='%bid %'
set #escapeSearch ='%[[]Bid]%'
select distinct so.name
from syscomments sc
inner join sysobjects so
on sc.id=so.id
where text like #objectSearch or text like #crlfSearch
or text like #escapesearch
This query looks for three common cases you might have to add some but basically we find where the table name has a space after it, (This helps to limit cases where the table name is part of another table name), Has a return at the end of it, or is escaped within brackets.