Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the text of a stored procedure into a variable in SQL Server

I want to loop through several stored procs and extract one string form each of them to use in another procedure (basically the 4-part remote server string)

So I can get the stored procs list from SysObjects (with Type = P) into a table, then I can loop or cursor through that table variable calling sp_helptext on each one.

But how can I get the text result of sp_helptext into a variable so I can do a CharIndex on the word 'BOCTEST' etc?

Is there a table like sys.procedures that stores the text.

like image 638
Our Man in Bananas Avatar asked Feb 11 '14 17:02

Our Man in Bananas


People also ask

How can we get stored procedure result in variable in SQL Server?

You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success. If no return is explicitly set, then the stored procedure returns zero. You should use the return value for status codes only.

How do I get all stored procedure text in SQL Server?

Using SQL Server Management Studio Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. Expand Stored Procedures, right-click the procedure and then select Script Stored Procedure as, and then select one of the following: Create To, Alter To, or Drop and Create To.

Can a procedure return a value?

A stored procedure does not have a return value but can optionally take input, output, or input-output parameters. A stored procedure can return output through any output or input-output parameter.


1 Answers

The portable way is to use the ANSI/ISO view INFORMATION_SCHEMA.ROUTINES, but you'll only get the first 4000 characters of the stored procedure definition:

declare @source_code varchar(max)

select @source_code = t.ROUTINE_DEFINITION
from information_schema.routines t
where specific_schema = 'owner-schema'             -- e.g., dbo
  and specific_name   = 'my_stored_procedure_name' -- your stored procedure name here

Or you can use the system view sys.sql_modules in the same vein:

declare @source_code varchar(max)

select @source_code = definition
from sys.sql_modules
where object_id = object_id('dbo.my_stored_procedure_name')

Or, the simplest way:

declare @source_code varchar(max)
set @source_code = object_definition( 'dbo.my_stored_procedure_name' )
like image 126
Nicholas Carey Avatar answered Sep 20 '22 10:09

Nicholas Carey