2

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

4

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.

  • 1
    It is worth noting that the INFORMATION_SCHEMA is an ANSI standard - albeit not implemented by all systems (see list in link). – Vérace Jan 9 '20 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.