I am using SQL server 2012, & always use SP_HELPTEXT
to get my previously created Stored Procedures, In previous versions of SQL server there were no issues
The answer posted by Rufo still produces blank lines. A little change in the last line of code solved the issue for me. Here is the edited code:
CREATE PROCEDURE [dbo].[sp_helptext2] (@ProcName NVARCHAR(256))
AS
BEGIN
DECLARE @PROC_TABLE TABLE (X1 NVARCHAR(MAX))
DECLARE @Proc NVARCHAR(MAX)
DECLARE @Procedure NVARCHAR(MAX)
DECLARE @ProcLines TABLE (PLID INT IDENTITY(1,1), Line NVARCHAR(MAX))
SELECT @Procedure = 'SELECT DEFINITION FROM '+db_name()+'.SYS.SQL_MODULES WHERE OBJECT_ID = OBJECT_ID('''+@ProcName+''')'
insert into @PROC_TABLE (X1)
exec (@Procedure)
SELECT @Proc=X1 from @PROC_TABLE
WHILE CHARINDEX(CHAR(13)+CHAR(10),@Proc) > 0
BEGIN
INSERT @ProcLines
SELECT LEFT(@Proc,CHARINDEX(CHAR(13)+CHAR(10),@Proc)-1)
SELECT @Proc = SUBSTRING(@Proc,CHARINDEX(CHAR(13)+CHAR(10),@Proc)+2,LEN(@Proc))
END
--* inserts last line
insert @ProcLines
select @Proc ;
--edited here. (where Line<>'')
SELECT Line FROM @ProcLines where Line<>'' ORDER BY PLID
END
Even though this removes the "original carriage returns", but this is way better to live with. I migrated by DB from SQL 2008 to SQL 2012 and all the stored procedures (more than 200) were returned with around 5 carriage returns after every line of code when using sp_helptext.
The above code helped me resolve it.
I wrote another workaround that just replaces the CrLf:
DECLARE @results table ([Text] nvarchar(255))
INSERT @results
Exec sp_helptext spStudyRoleCacheFlushNotificationGet
SELECT REPLACE(REPLACE([Text], CHAR(10), ''), CHAR(13), '')
FROM @results