|
|
|
In SQL Server anything text longer than 8000 characters can be stored in TEXT or NTEXT datatype column but when you use TEXT or NTEXT datatype is not same as regular char, varchar, nchar or nvarchar datatype. You can not use string function like ltrim, rtrim, replace etc... Then how do you search and replace ????
Here is the stored proc which will replace specified text with new text. |
Click here to copy the following block |
create proc usp_SearchReplaceText @str_find varchar(8000) ,@str_replace varchar(8000) ,@table_name varchar(128) ,@text_col varchar(128) as declare @cmd varchar(8000)
set @cmd= ' set xact_abort on begin tran
declare @str_find varchar(1000) set @str_find = ''' + replace(@str_find,'''','''''') + ''' declare @str_replace varchar(1000) set @str_replace = ''' + replace(@str_replace,'''','''''') + ''' declare @txtlen int set @txtlen = len(@str_find) declare @ptr binary(16) declare @pos int
declare curs cursor local fast_forward for select textptr(' + @text_col + '), charindex(@str_find, ' + @text_col + ')-1 from ' + @table_name + ' where ' + @text_col + ' like ''%'' + @str_find +''%'' open curs fetch next from curs into @ptr, @pos while @@fetch_status = 0 begin updatetext ' + @table_name + '.' + @text_col + ' @ptr @pos @txtlen @str_replace fetch next from curs into @ptr, @pos end close curs deallocate curs
commit tran '
execute(@cmd) go |
Click here to copy the following block |
create table test( myid int ,memo text ) go
insert into test values (1,'aaa') insert into test values (2,'bbb') go
Print 'Before replace' select * from test
go
exec usp_SearchReplaceText 'aaa','new_aaa','test','memo'
go
Print 'After replace' select * from test |
Before replace
myid memo
----------- -------
1 aaa
2 bbb
After replace
myid memo
----------- --------
1 new_aaa
2 bbb |
|
|
|
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 ) |
|
|