views:

509

answers:

1

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.

+2  A: 

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)
Robin Day
very good. Why didn't I think of that...
gbn
Of course it wont work if the requirement is to replace the first 4 with 1 and the second 4 with 0 rather than replace 44 with 10. In that case you would need to call the function twice.
Robin Day
@gbn: because its monday :)
Robin Day