SQL Server - 按外观替换字符串
Posted
技术标签:
【中文标题】SQL Server - 按外观替换字符串【英文标题】:SQL Server - replace string by appearance 【发布时间】:2020-05-26 19:08:31 【问题描述】:有个小问题……这是测试数据
CREATE TABLE #TestReplace (
Description NVARCHAR(500)
,ParamValue1 INT
,ParamValue2 INT
,ParamValue3 INT
);
INSERT INTO #TestReplace (Description)
VALUES ('This sentence has no parameteres, and it should be shown like this');
INSERT INTO #TestReplace (
Description
,ParamValue1
)
VALUES (
'This sentence has only one parametere, and it should be shown right here param with rest of text'
,100
);
INSERT INTO #TestReplace (
Description
,ParamValue1
,ParamValue2
)
VALUES (
'This sentence has two parameteres, one here param and one here param, show full sentence'
,100
,200
);
INSERT INTO #TestReplace (
Description
,ParamValue1
,ParamValue2
,ParamValue3
)
VALUES (
'This sentence has all parameteres, here param and here param and there param'
,100
,200
,300
);
在我的句子中,我有时会或从不出现单词param
...和列ParamValue1
、ParamValue2
、ParamValue3
...我如何将第一次出现的单词param
替换为列ParamValue1
的值,第二个字param
与列ParamValue2
的值和第三个与列ParamValue3
的值...我无法将字param
更改为param1
、param2
和@ 987654335@ 并进行简单替换
到目前为止,我设法只替换了第一次出现...
SELECT CASE
WHEN CHARINDEX('param', DESCRIPTION) > 0
THEN STUFF(DESCRIPTION, CHARINDEX('param', DESCRIPTION), LEN('param'), ParamValue1)
ELSE DESCRIPTION
END
FROM #TestReplace
这在 Oracle 中很容易管理 (Oracle - replace string by appearance)
【问题讨论】:
SQL Server 本身不支持 REGEX,因此不支持 REGEX 替换。如果您确实想要这样的东西,您可能需要查看 CLR 函数。 您的 SQL Server 版本是多少? 目前在 Microsoft SQL Server 2012 上,但可以根据需要进行更新 【参考方案1】:您可以使用APPLY
将它们链接在一起:
SELECT COALESCE(v3.DESCRIPTION, v2.DESCRIPTION, v1.DESCRIPTION, tr.DESCRIPTION)
FROM #TestReplace tr CROSS APPLY
(VALUES (CASE WHEN tr.Description LIKE '%param%'
THEN STUFF(tr.DESCRIPTION, CHARINDEX('param', tr.DESCRIPTION), LEN('param'), tr.ParamValue1)
END)
) v1(description) CROSS APPLY
(VALUES (CASE WHEN v1.Description LIKE '%param%'
THEN STUFF(v1.DESCRIPTION, CHARINDEX('param', v1.DESCRIPTION), LEN('param'), tr.ParamValue2)
END)
) v2(description) CROSS APPLY
(VALUES (CASE WHEN v2.Description LIKE '%param%'
THEN STUFF(v2.DESCRIPTION, CHARINDEX('param', v2.DESCRIPTION), LEN('param'), ParamValue3)
END)
) v3(description);
【讨论】:
以上是关于SQL Server - 按外观替换字符串的主要内容,如果未能解决你的问题,请参考以下文章
sql server 将字符串第二字符替换为另外一个字符的 方法