Wednesday, 8 June 2011

T-SQL Simple Search & Replace on Table Content

This was thrown together in an attempt to save some time having to edit a hefty amount of text content. Simple amend the below script with your table, field, text you want replaced, what you want to replace it with and hey ho - you've hacked your content!

DECLARE @TABLE  VARCHAR(30) 
DECLARE @FIELD VARCHAR(30) 
DECLARE @WHERE VARCHAR(100) 
DECLARE @FIND VARCHAR(100) 
DECLARE @REPLACEWITH  VARCHAR(100) 
DECLARE @query VARCHAR(8000) 

SET @TABLE = 'MyTableName' 
SET @FIELD= 'MyField'
SET @FIND =  'text i want replacing' 
SET @REPLACEWITH = 'new text' 

BEGIN     
SET @query  = 
'UPDATE ' +  @TABLE +      
' SET ' +  @FIELD + 
'= REPLACE(CONVERT(varchar(8000),'     + 
@FIELD + '),''' +  @FIND + ''',''' + 
@REPLACEWITH  +''')'   

EXECUTE (@query) END 
GO


No comments:

Post a Comment