Remove comments from the SQL Code

This function takes in a varchar(max) as input and strips out all the comments and RETURNS that string. It replaces comments with a carriage return character; this behavior can be easily changed by find/replacing the char(13) in the code to a single space ' '.

Start a while look; while loop exits if it can't find anymore /* in the input string:
1a. Find the first ending '*/'
1b. Truncate everything after that
1c. Reverse the string and find the first occurance of '*/' again; since the string is reversed, we;d have to look for */ instead of /*
1d. Calculate the comment length
1e. Replace comment with char(13)

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands
of articles and SQL scripts, a library of free eBooks, a weekly database news roundup,
a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals
that makes it such a success.