我需要用[contact.FirstName]替换字符串%% firstName %%和[contact.LastName]替换%% lastName %%,但是这些字符串可以在字段中的任何位置找到 例子
欢迎登机%% specialfield2 | fallback = |||||| %% %% firstname %% %% lastname %%
我需要这个成为
欢迎登机%% specialfield2 | fallback = |||||| %% [contact.FirstName] [contact.LastName]
请注意,第一个%%specialfield2|fallback=||||||%%
保持不变
使用下面的查询将查找%% first .. %%的首次出现并删除其余的
> SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT SUBJECT,
> REPLACE((CASE WHEN SUBSTRING(SUBJECT, CHARINDEX('%%', SUBJECT) + 1,
> LEN(SUBJECT) - CHARINDEX('%%', SUBJECT) - CHARINDEX('%%',
> REVERSE(SUBJECT)) ) LIKE '%Firstname%' OR SUBSTRING(SUBJECT,
> CHARINDEX('%%', SUBJECT) + 1, LEN(SUBJECT) - CHARINDEX('%%', SUBJECT)
> - CHARINDEX('%%', REVERSE(SUBJECT)) ) LIKE '%First name%' THEN REPLACE (SUBJECT, SUBSTRING(SUBJECT, CHARINDEX('%%', SUBJECT) + 1,
> LEN(SUBJECT) - CHARINDEX('%%', SUBJECT) - CHARINDEX('%%',
> REVERSE(SUBJECT)) ),'[Contact.First Name]') ELSE SUBJECT END),'%','')
>
> FROM CAMPAIGN
CREATE TABLE #tab ( SUBJECT VARCHAR (100))
INSERT INTO #tab
SELECT 'Welcome Aboard %%specialfield2|fallback=||||||%% %%firstname%% %%lastname%%'
SELECT * FROM #tab
DROP TABLE #tab
通过运行此查询,我可以隔离%% %%
之间的字符串SELECT SUBJECT
, SUBSTRING(
SUBJECT,
CHARINDEX('%%', SUBJECT) + 1,
LEN(SUBJECT) - CHARINDEX('%%', SUBJECT) - CHARINDEX('%%', REVERSE(SUBJECT))
)
FROM #tab
答案 0 :(得分:0)
您唯一会遇到问题的地方是,如果您使用%的 WHERE 子句。 REPLACE 只是将找到的子字符串替换为另一个子字符串。
让我们从这开始吧。我已将%% firstname %%和%% lastname %%放在不同的地方。
CREATE TABLE #tab
(
SUBJECT VARCHAR(100)
)
INSERT #tab select 'Welcome Aboard %%specialfield2|fallback=||||||%% %%firstname%% %%lastname%%'
INSERT #tab select 'Welcome Aboard %%specialfield2|fallback=||||||%%%%lastname%% %%firstname%% test here'
INSERT #tab select 'Welcome Aboard %%firstname%%%%lastname%% %%specialfield2|fallback=||||||%%'
INSERT #tab select 'Welcome Aboard %%firstname%% %%specialfield2|fallback=||||||%% %%lastname%%'
INSERT #tab select 'Welcome Aboard'
你可以这样做:
UPDATE #tab set [SUBJECT]=REPLACE(REPLACE([SUBJECT], '%%firstname%%', '[contact.FirstName]'), '%%lastname%%', '[contact.LastName]')
如果你想要WHERE子句,你必须逃避%:How do I escape a percentage sign in T-SQL?
UPDATE #tab set [SUBJECT]=REPLACE(REPLACE([SUBJECT], '%%firstname%%', '[contact.FirstName]'), '%%lastname%%', '[contact.LastName]')
WHERE [SUBJECT] LIKE '%[%][%]%name[%][%]%'