Description:
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 ' '.
Purpose:
- Returns text with out any comments in it.
- Handles commet like "--"
- Handles comments like /* some text */
/* some text
/* some text */
some more text
*/
Usage Example:
USE tempdb GO DECLARE @def varchar(100) = ' hello /* first */ hell0 2 /* second /* third */-second */ --third world' PRINT dbo.UtilFn_RemoveComments (@def) GO
Algorithm Logic:
1. Handling nested /*..*/ type comments
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)
1f. repeat until you can't find any more /*
2. Handling '--' type comment
2a. Find starting point of '--'
2b. Get the entire string length after that
2c. Replace comment with char(13)