Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace last occurance of a string 3

Status
Not open for further replies.

xpblueScreenOfDeath

Programmer
Sep 1, 2004
87
Is there a easy way to replace the last occurance of a string with another string and how to do it?

Example:
a, b, c, d.

Replace last "," with "and", so the outcome will be:

a, b, c and d.
 
here...run this in query analyzer...

Code:
declare @i as varchar (50)
set @i = '1, 2, 3'

print reverse(@i)

set @i = reverse(@i)

print reverse(left(@i,charindex(',',@i) - 1) + 'dna ' + right(@i,charindex(',',@i) + 1))
 
This is a little ugly, bt it works. It may need a little tweaking.

Code:
Declare @Example VarChar(100)

Set @Example = 'a, b, c, d'

Select 	Left(@Example, Len(@Example) - charindex(',', Reverse(@Example))) +
		replace(Right(@Example, charindex(',', Reverse(@Example))), ',', ' and')

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
I don't see the issues checkai, but I'd use Stuff.
Code:
[Blue]DECLARE[/Blue] @i [Blue]AS[/Blue] [Blue]varchar[/Blue] [Gray]([/Gray]50[Gray])[/Gray]
[Blue]SET[/Blue] @i [Gray]=[/Gray] [red]'1, 2, 3'[/red]
[Blue]PRINT[/Blue] [Fuchsia]Reverse[/Fuchsia][Gray]([/Gray]@i[Gray])[/Gray]
[Blue]SET[/Blue] @i [Gray]=[/Gray] [Fuchsia]Reverse[/Fuchsia][Gray]([/Gray]@i[Gray])[/Gray]
[Blue]PRINT[/Blue] [Fuchsia]Reverse[/Fuchsia][Gray]([/Gray][Fuchsia]Stuff[/Fuchsia][Gray]([/Gray]@i[Gray],[/Gray] [Fuchsia]CharIndex[/Fuchsia][Gray]([/Gray][red]','[/red][Gray],[/Gray]@i[Gray])[/Gray][Gray],[/Gray]1[Gray],[/Gray][red]'dna '[/red][Gray])[/Gray][Gray])[/Gray]
-Karl

[red] Cursors, triggers, user-defined functions and dynamic SQL are an axis of evil![/red]
[green]Life's uncertain...eat dessert first...www.deerfieldbakery.com[/green]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top