Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Generic logic to search & replace characters in a string.

Total Hit ( 1515)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


A generic logic to search & replace certain characters in a string. This approach is flexible in the sense that new characters can be added for searching without modifying the logic. This will make the code more maintainable too.

Click here to copy the following block
CREATE TABLE #ReplChars (
LookFor char( 1 ) ,
ReplaceWith char( 1 ) DEFAULT ( '_' )
)
GO
INSERT INTO #ReplChars VALUES( '/' , DEFAULT );
INSERT INTO #ReplChars VALUES( '*' , DEFAULT );
INSERT INTO #ReplChars VALUES( '?' , DEFAULT );
GO

/* SQL6x version using the STUFF function */
DECLARE @Str varchar(30 )
SELECT @Str = 'abc.07/07/2000*x?'
WHILE( EXISTS( SELECT * FROM #ReplChars
       WHERE CHARINDEX( LookFor , @Str ) > 0 ) )
  SELECT @Str = STUFF( @Str , CHARINDEX( LookFor , @Str ) , 1 , ReplaceWith )
  FROM #ReplChars
  WHERE CHARINDEX( LookFor , @Str ) > 0
PRINT @Str


/* SQL70 version queries using the new REPLACE function */
DECLARE @Str varchar(30 )
SELECT @Str = 'abc.07/07/2000*x?'
WHILE( EXISTS( SELECT * FROM #ReplChars
       WHERE CHARINDEX( LookFor , @Str ) > 0 ) )
  SELECT @Str = REPLACE( @Str , LookFor , ReplaceWith )
  FROM #ReplChars
  WHERE CHARINDEX( LookFor , @Str ) > 0
PRINT @Str

-- Or the T-SQL update extension
SELECT @Str = 'abc.07/07/2000*x?'
UPDATE #ReplChars
SET @Str = REPLACE( @Str , LookFor , ReplaceWith )
WHERE CHARINDEX( LookFor , @Str ) > 0
PRINT @Str

DROP TABLE #ReplChars


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.