Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

Remove comments from the SQL Code

By Shivaram Challa,


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 ' '.


  • 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

DECLARE @def varchar(100) = '
hello /* first */ hell0 2 /* second /* third */-second */ --third
PRINT dbo.UtilFn_RemoveComments (@def)

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)

Total article views: 1871 | Views in the last 30 days: 10
Related Articles

Tame Those Strings! Part 3 - Using REPLACE

The third part of Steve Jones's series on programming and manipulating strings in T-SQL dealing with...


Replacing strings

Replacing data


Find and Replace a String in the Whole Database

Find and Replace a string in all string fields (char, varchar, etc) of all tables in the database.


How to replace first occurrance of pipe delimeter

How to replace first occurrance of pipe delimeter


Performance and handling differences for tally function across servers

string cleaning function using tally table loop handled differently