Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the text of a stored procedure in SQL Server

I am trying to save an old stored procedure into a string. When I use the following I do not get any line breaks.

SELECT @OldProcedure = Object_definition(object_id)
FROM   sys.procedures
WHERE  name = @ProcedureName

Any suggestions on how to get the stored procedure text with the line breaks?

I was thinking of using sp_helptext

Thanks

Update

I am copying and pasting the results from the results which will show me a single line.

As for the script as I am storing the results in a db field. I am create a tool that will generate procedures on the fly, but I wanted to create a history of them.

Update

Turned out the Object_definition does what I want, But for some reason when I copy it from the results I get a single line.

Declare @sql varchar(max) ;
SELECT @sql=Object_definition(object_id)
FROM   sys.procedures
WHERE  name = 'Test_QueryBuilder';

drop procedure Test_QueryBuilder
exec( @sql)
print @sql
like image 454
H20rider Avatar asked May 15 '15 19:05

H20rider


2 Answers

I've recently come across the same question and made a quick and dirty script to get the definition of views, but the very same thing could also work for stored procedures and functions.

DECLARE @Lines TABLE (Line NVARCHAR(MAX)) ;
DECLARE @FullText NVARCHAR(MAX) = '' ;

INSERT @Lines EXEC sp_helptext 'sp_ProcedureName' ;
SELECT @FullText = @FullText + Line FROM @Lines ; 

PRINT @FullText ;

It simply uses sp_helptext as you suggested, grabs its output in a table variable and concatenates all the resulting lines into a text variable. It also uses the fact that each line in the sp_helptext result set includes the trailing new line character, so no need to add it here.

From there on, you just use the variable as you would do normally, print it, save to some table or do some manipulation on it. My particular use case was to build a helper stored procedure to drop a view and recreate it when modifying its underlying tables.

like image 164
Alejandro Avatar answered Oct 17 '22 14:10

Alejandro


Two ways:

select name, object_definition(object_id) 
from sys.procedures

or

select object_name(p.object_id), definition
from sys.sql_modules as m
join sys.procedures as p
   on m.object_id = p.object_id
like image 26
Ben Thul Avatar answered Oct 17 '22 12:10

Ben Thul