Question

I don't readily see anything in the sys schema objects, other than the DM_EXEC_SQL_TEXT function that requires a plan handle, but the procedures I'm trying to get their query texts from aren't currently running. (Maybe there's a way through their cached plans?...though the ones I'm looking for might not have a cached plan.)

Are the query texts of stored procedures stored anywhere that's queryable?

I see sp_helptext might be an option: https://docs.microsoft.com/en-us/sql/relational-databases/stored-procedures/view-the-definition-of-a-stored-procedure?view=sql-server-ver15#TsqlProcedure

Was it helpful?

Solution

There are several ways to get this that require different input information

INFORMATION_SCHEMA:

You only need to know the name of the object you want the definition for.

SELECT ROUTINE_NAME, ROUTINE_DEFINITION 
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME = 'MyProcName'

Note, this schema is database specific, so you need to be in the context of the database where the procedure exists for this query to return the correct data. Also note, it only returns the first 4000 characters of the procedure.

OBJECT_DEFINITION:

You need to know the object_id of the procedure you're looking for.

SELECT OBJECT_DEFINITION(*object_id*)

Database-specific as well, but returns the complete text of the object.

sys.sql_modules:

You need to know the object_id of the procedure you're looking for.

SELECT * FROM sys.sql_modules WHERE object_id = *object_id*

Database-specific as well, but returns the complete text of the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top