phill
phill

Reputation: 13844

tsql : how to do a substring replace?

goal: I have the string "1234432144" I want to only replace the first 2 4's with '10' so I would get '1231032144'

Is there a way to do this in tsql?

so far I have come up with the tsql substring() function

substring('1234432144', 4, 2) 

which draws the 44 .. however how do i replace it within the existing string?

If i wrap a replace function around it, it replaces all occurrences of 44 in the string.

any ideas?

thanks in advance.

Upvotes: 4

Views: 5891

Answers (1)

Robin Day
Robin Day

Reputation: 102468

Edited with a paremeterised version.

DECLARE @myStr VARCHAR(50)
DECLARE @findStr VARCHAR(50)
DECLARE @replaceStr VARCHAR(50)

SET @myStr = '1234432144'
SET @findStr = '44'
SET @replaceStr = '10'

SELECT STUFF(@myStr, CHARINDEX(@findStr, @myStr), LEN(@findStr), @replaceStr)

Upvotes: 5

Related Questions