Snippet - MSSQL Print Stored Procedures

You want to send a copy of your MSSQL database’s stored procedures to someone outside your organization or otherwise doesn’t have access to your system. This T-SQL will output all of them, so you can copy it and send it away.


----- your database name

use database_name

----- / your database name

/*
1. Run this script in your query browser,
2. look at the output. Select all of the output (control+a is the hotkey)
3. copy all of the output (control+c to copy) and paste (control+v to paste) it into Notepad
4. save the file as StoredProcedures.sql
*/

declare @temptable table
(id int identity(1,1),
name varchar(1000))

declare @sptemptable table
(id int identity(1,1),
text nvarchar(4000))

declare @i int, @count int, @name varchar(1000), @text nvarchar(4000)

insert into @temptable
SELECT ROUTINE_NAME 
	FROM INFORMATION_SCHEMA.ROUTINES 
	WHERE 
		ROUTINE_TYPE = 'PROCEDURE' 
		AND OBJECTPROPERTY 
		( 
			OBJECT_ID(ROUTINE_NAME), 
			'IsMsShipped' 
		) = 0 
	ORDER BY ROUTINE_NAME 

select @count = COUNT(*) from @temptable
set @i=1
while @i<@count+1
BEGIN
	set @name = null
	select @name = name from @temptable where id = @i
	INSERT INTO @sptemptable (text)
	exec sp_helptext @name
	set @i=@i+1
END

select @count = COUNT(*) from @sptemptable
set @i = 1
while @i < @count + 1
BEGIN
	select @text = TEXT from @sptemptable where id = @i
	print @text
	set @i=@i+1
END


Author: Matthew Poer
Last Edited: Jan 12, 2011