我有一个名为EmailTemplates
的表,其中包含MessageText
列。对于每一行,我想在Please review details
之前添加Thank you
。对于某些行,可能会在thank you
之后发送文字。
BEFORE
All the correspondence will be sent to your address.
Thank you!
AFTER
All the correspondence will be sent to your address.
Please review details
Thank you!
我不知道REPLACE
是否是正确的功能。
答案 0 :(得分:1)
试试这个:
UPDATE EmailTemplates
SET MessageText = LEFT(MessageText, LEN(MessageText) - 10) + 'Please review details.
Thank You!'
答案 1 :(得分:1)
这实际取决于您是否要将“谢谢”的所有实例替换为“请查看详细信息谢谢”或仅替换最后一个。下面的实现,虽然非常hacky,向您展示了如何做到这两点(虽然如果这是生产用途,我强烈建议重构代码,以减少它的混乱)。
declare @myTestTable as table
(
id int identity(1,1) not null primary key clustered,
textValue varchar(500) not null
);
insert into @myTestTable(textValue)
values
('All correspondence will be sent to your addres. Thank you!'),
('I will get back to you. Thank you for your patience'),
('Thank you for calling us up'),
('You didn''t have to do what you did, but I thank you for it, so thank you!');
select m.*, REPLACE(m.textValue, 'thank you', 'Please review details. Thank you') as blindReplace,
SUBSTRING(m.textValue, 0, len(m.textValue) - CHARINDEX(reverse('thank you'), reverse(m.textValue)) + 2 - len('thank you'))
+ 'Please review details ' +
SUBSTRING(m.textValue, len(m.textValue) - CHARINDEX(reverse('thank you'), reverse(m.textValue)) + 2 -len('thank you'), len(m.textValue)) as lastReplace
from @myTestTable as m
答案 2 :(得分:0)
REPLACE
可以在你的情况下使用,如何使用它的一个例子是@juergen现在删除的答案d:这里再次(稍微改为更好)匹配):
UPDATE EmailTemplates
SET MessageText = REPLACE(ColumnName, 'Thank you!', 'Please review details.
Thank you!')
WHERE MessageText LIKE '%Thank you!%';
您可以使用上述多线替换字符串,也可以使用CHAR(13)+CHAR(10)
对EOL进行编码:
REPLACE(
ColumnName,
'Thank you!',
'Please review details.' + CHAR(13)+CHAR(10) + CHAR(13)+CHAR(10) + 'Thank you!'
)
还有使用STUFF
和CHARINDEX
的方法:
UPDATE EmailTemplates
SET MessageText = STUFF(
ColumnName,
CHARINDEX('Thank you!', ColumnName),
0,
'Please review details.
'
)
WHERE MessageText LIKE '%Thank you!%';
这种方法当然更加冗长。从技术上讲,它并不完全等同于REPLACE
,因为REPLACE
处理搜索词的所有出现,而STUFF
仅适用于字符串的一个特定位置/片段。但是如果Thank you!
在模板中不能出现多次,则可以认为这两种方法是等效的。