Jin Yong
Jin Yong

Reputation: 43778

How can I replace the last comma in the string to "and" in SQL Server

Just wandering, how can I replace the last comma in the string to "and" in SQL Server.

I have the following valuable:

@test = 'a,b,c,f,w'

How can I replace the last comma in the string to "and" as the output:

'a,b,c,f and w' 

Upvotes: 3

Views: 1364

Answers (2)

Md. Suman Kabir
Md. Suman Kabir

Reputation: 5453

Another way to achieve it :

SELECT reverse(STUFF(reverse(@test), CHARINDEX(',', reverse(@test)), 1, ' dna '))

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269873

That is weird. You can do:

set @test = left(@test, len(@test) - charindex(',', reverse(@test))) + ' and ' + stuff(@test, 1, len(@test) - charindex(',', reverse(@test)) + 1, '')

Upvotes: 1

Related Questions