declare @str varchar(50)=\'GoodLuck Markand\'
declare @replacedString varchar(50)
set @replacedString = replace(@str,\'Good\',\'Better\')
print @replacedString
Append empty space
at start and end of the string then replace ' Good '
with ' Better '
. Finally use Ltrim
and Rtrim
to remove the empty space at start and end of the string
DECLARE @str VARCHAR(50)='Good Luck Good MarkandGood Good'
DECLARE @replacedString VARCHAR(50)
SELECT rtrim(ltrim(Replace(replace(' '+@str+' ',' Good ',' Better '),
' Good ',' Better ')))
Try This: (Works as Expected)
declare @str varchar(500)
set @str = 'Good Good Good Good Good Good Good Good Luck Good GoodLuck MarkAndGood GoodMarkAnd MarkAndGood Good'
declare @replacedString varchar(500)
SET @replacedString = replace(@str,' Good ',' Better ')
SET @replacedString = replace(@replacedString,' Good ',' Better ')
SET @replacedString = CASE WHEN CHARINDEX('Good ', @replacedString) = 1 THEN
STUFF(@replacedString, 1, Len('Good'), 'Better')
ELSE @replacedString END
SELECT CASE WHEN CHARINDEX(REVERSE(' Good'), REVERSE(@replacedString)) = 1 THEN
Reverse(STUFF(Reverse(@replacedString), CHARINDEX(Reverse(' Good'),
Reverse(@replacedString)), Len(' Good'), Reverse(' Better')))
ELSE @replacedString END AS A
Input:
Good Good Luck Good GoodLuck Good
Result:
Better Better Luck Better GoodLuck Better
This does not seems to be functionality of Replace, as per MSDN; You have to use give spaces at both side of the word being searched and replaced.
replace(@str,' Good ',' Better ')
Replaces all occurrences of a specified string value with another string value.
Refer MSDN
Syntax
REPLACE ( string_expression , string_pattern , string_replacement )
Arguments
string_expression Is the string expression to be searched. string_expression can be of a character or binary data type.
string_pattern Is the substring to be found. string_pattern can be of a character or binary data type. string_pattern cannot be an empty string (''), and must not exceed the maximum number of bytes that fits on a page.
string_replacement Is the replacement string. string_replacement can be of a character or binary data type.