问题
In T-SQL, how do I replace the occurrence of a substring only at the end of a character string (varchar)?
For example:
If I were to do the operation with substring violence on character string 'violence begets violence', the result would be 'violence begets '
Some other examples are
1)'the fox jumped over the fence' with substring fox would result in no change as fox is not at the end of the character string.
2)Can I kick the can with substring can would result in Can I kick the
3)gs_fs_pringles with substring _fs would result in no changes
4)gs_pringles_fs with substring _fs would result in gs_pringles
回答1:
DECLARE @t TABLE(SomeString varchar(100))
INSERT @t VALUES ('violence begets violence'), ('the fox jumped over the fence'), ('Can I kick the can');
WITH CTE1 AS (
SELECT
CHARINDEX(' ', SomeString) AS LeftIndex,
REVERSE(CHARINDEX(' ', SomeString)) AS RightIndex,
RTRIM(SomeString) AS SomeString
FROM
@t
), CTE2 AS (
SELECT
LEFT(SomeString, LeftIndex-1) AS LeftWord,
RIGHT(SomeString, RightIndex-1) AS RightWord,
LeftIndex, RightIndex, SomeString
FROM
CTE1
)
SELECT
CASE
WHEN LeftWord <> RightWord THEN SomeString
ELSE LEFT(SomeString, LEN(SomeString)-RightIndex)
END
FROM
CTE2;
回答2:
The following ignores trailing spaces. If that is not a problem, please give it a try:
SELECT
acolumn = CASE
WHEN LEN(acolumn) < LEN(@substring)
THEN acolumn
ELSE LEFT(acolumn, x.cutpos)
+ REPLACE(SUBSTRING(acolumn, x.cutpos + 1, 999999), @substring, '')
END
FROM atable
CROSS APPLY (SELECT LEN(acolumn) - LEN(@substring)) x (cutpos)
;
The query works like this:
If the length of the column value is less than the length of the argument substring, the entire column value is returned.
Otherwise, the original value is divided into two pieces: the same number of characters as in the argument is cut out from the right, the rest of the value forms the left part.
If the right part "contains" (but in fact is equal to) the argument, it is replaced with an empty string, otherwise it remains unchanged.
In either event, the result is concatenated back to the left part of the original value to form the final output value.
There's also a SQL Fiddle for you to play with.
来源:https://stackoverflow.com/questions/16839806/replace-substring-specifically-at-the-end-of-the-character-string-in-sql