根据其他列值进行条件替换

Dav*_*ips 1 sql conditional replace

我有一个包含表的数据库:

********************************
* Code  *      FileName        *
********************************
* NULL  * Cats and Dogs        *
* C123  * C123 - Cats and Dogs *
* NULL  * Baking Cakes         *
* Z345  * Z345 - Plants        *
* F967  * E345 - Tractors      *
********************************
Run Code Online (Sandbox Code Playgroud)

我想返回所有行的文件名或操纵文件名,基于代码列中是否有值并且它与文件名中的代码匹配。

所以查询应该返回

Cats and Dogs
xxxx - Cats and Dogs
Baking Cakes
xxxx - Plants
E345 - Tractors
Run Code Online (Sandbox Code Playgroud)

从上面的一组数据来看。

我正在努力对另一列中的值进行条件替换 - 如果我使用 case 语句进行替换,我需要列出所有可能的代码,这将很难维护。有什么办法吗

Select Replace(FileName, Code, "xxxx") from table where filename like %Code%
Run Code Online (Sandbox Code Playgroud)

Tim*_*sen 6

您可以尝试以下查询:

SELECT
    CASE WHEN Code IS NULL
         THEN FileName
         ELSE REPLACE(FileName, Code + ' - ', 'xxxx - ') END AS label
FROM yourTable;
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

演示

WHERE此处不一定需要子句,因为替换逻辑已经检查是否存在匹配项。请注意,我搜索code -,即您期望的上下文中的代码。这至少部分地减轻了可能存在错误替换的可能性。