views:

426

answers:

3

User SQLServer 2005 Here is an example of string I'm stuck with: {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Arial Rounded MT Bold;}{\f1\fnil\fcharset0 Arial;}} \viewkind4\uc1\pard\f0\fs54 1000\f1\fs20\par }

I want to replace any font name with 'Times New Roman'

I can get the first one with (textlong1 is the field):

 Select Replace(textlong1, 
        CASE When CharIndex(';',textlong1)> 10 Then
        SubString(textlong1
        , Charindex('fcharset',textlong1)+10
        , CharIndex(';',textlong1) - Charindex('fcharset',textlong1)-10) 
        Else '' End
        , 'Times New Roman') From exampletable

I'm using the case statement to prevent the SubString from error.

Since I am not replacing 'fcharset', even if I loop through, it is not finding the second instance (always gets stuck on the first).

A: 

You could always use a delimiter procedure to break the string around the instances of your list of fonts and replace them with times new roman.

DForck42
Did you mean delimiter? Trying to do a search.
Jeff O
yes, that's what i mean
DForck42
+2  A: 

If you can integrate the .NET CLR functionality (MSDN has many examples for doing that), you could use a regex replace and make your task very simple.

Alex Martelli
It is a 3rd party application using this database (If I had more control of the front-end, I wouldn't allow this nonsense.). I'll have to see if this will create a problem.
Jeff O
Yeah, I realize .NET CLR integration is not always practical (no matter how much MSDN pushes it;-), that's why I said "if you can". If you can't, workarounds as suggested in other answers are all you're left with.
Alex Martelli
the only real problem is that from what i've heard inefficient use of CLR creates an extreamly high overhead.
DForck42
+1  A: 

If you can replace the first one, just keep replacing till there is no first one. If you're doing an update:

declare @done bit
while @done <> 1
    begin
    UPDATE ...
    if @@rowcount = 0 set done = 1
    end

Or selecting into a new variable:

declare @cur varchar(4000)
declare @next varchar(4000)
set @cur = 'The string to operate on'
set @next = ''
while @cur <> @next
    begin
    set @next = @cur
    select @cur = REPLACE(@next,...)
    end

The final result is now stored in @cur (and @next too.)

Andomar
Since I am not replacing 'fcharset', I can't get the replace to 'skip' the first corrected one (See edit I made.).
Jeff O
Replace all "fcharset0 Times New Roman" with "fcharset0 Arial Rounded MT Bold" before you start. Every loop iteration, start the search at index 1, or after the first occurance of "fcharset0 Times New Roman".
Andomar
Thanks for the help. I added the followingdeclare @Start int--included this in all CharIndex functions as the start--last line of While Loop: SET @Start = Charindex(';',@next, @Start)
Jeff O