gpt4 book ai didi

SQL Server-按外观替换字符串

转载 作者:行者123 更新时间:2023-12-03 16:11:57 25 4
gpt4 key购买 nike

有一个小问题...这是测试数据

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},或者永远不会出现...,而列 ParamValue1ParamValue2ParamValue3 ...如何将单词 {param}的第一次出现替换为 ParamValue1列的值,将第二个单词 {param}替换为 ParamValue2列的值第三列带有 ParamValue3列的值...我无法将单词 {param}更改为 {param1}{param2}{param3}并进行简单替换

到目前为止,我设法只替换了第一次出现的情况...
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)中可以轻松地对此进行管理

最佳答案

您可以使用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-按外观替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com