Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
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 Shiva Challa,

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)

Total article views: 1746 | Views in the last 30 days: 15
 
Related Articles
ARTICLE

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

FORUM

Replacing strings

Replacing data

SCRIPT

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.

FORUM

How to replace first occurrance of pipe delimeter

How to replace first occurrance of pipe delimeter

FORUM

Performance and handling differences for tally function across servers

string cleaning function using tally table loop handled differently

Tags
 
Contribute

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.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones