-4

I want to update the substring between the two first successive parameter I want to write a query which will do the same effect as the example below , johnold is just an example

a= 'parameterjohnoldparameter123parameter'
b='aaa'

result would be

a= 'parameteraaaparameter123parameter'

How can I do something like that ?

2
  • 1
    on what basis replace b ?wht should i look for ?explain.
    – KumarHarsh
    Dec 20, 2013 at 15:30
  • Is there any text before the first parameter or will the first value always be found at position 10?. Dec 20, 2013 at 15:41

5 Answers 5

3

You can stuff it in there.

declare @a varchar(30)
declare @b varchar(30)

set @a = 'parameterjohnoldparameter123'
set @b = 'aaa'

select stuff(@a, 10, 7, @b)
-- or do a search for the second parameter string
select stuff(@a, 10, charindex('parameter', @a, 10) - 10, @b)
1
  • +1 Better than my answer, assuming the part to be replaced works on ordinal position and is fixed length rather than being a specific value.
    – Bridge
    Dec 20, 2013 at 15:35
1

I guess you're looking for:

SET a = REPLACE(a, 'johnold', b)

But how do we know what the part of the string you want to replace in the first string is? I've just guessed based on your example.

0

To change in a single table

 UPDATE `table_name`
 SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')
0

From: http://technet.microsoft.com/en-us/library/ms186862.aspx

REPLACE( string_expression , string_pattern , string_replacement )

example:

SELECT REPLACE('Hello World', 'Hello', 'Goodbye Cruel')
GO
0

To avoid using fixed length or searching parameters you can use:

declare @a varchar(max),@b varchar(max),@c varchar(max)

set @a = 'parameterjohnoldparameter123parameter' --original row
set @b = 'aaa' --value to insert
set @c = 'parameter' --value to insert after it

select stuff(@a, LEN(@c)+1, charindex(@c, @a, LEN(@c)+1) - LEN(@c)-1, @b)

Or even calculate LEN(@c) one time before select.

1
  • Because we don't know max length of each parameter: a,b,c. I used "max", but if author knows the real max value (for example, replaceable part is from some column varchar(100)), we can use exact value. I understand that "max" isn't good idea for performance. Dec 21, 2013 at 6:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.