条件替换取决于其他列值

时间:2018-06-04 14:52:05

标签: sql replace conditional

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

********************************
* Code  *      FileName        *
********************************
* NULL  * Cats and Dogs        *
* C123  * C123 - Cats and Dogs *
* NULL  * Baking Cakes         *
* Z345  * Z345 - Plants        *
* F967  * E345 - Tractors      *
********************************

我想为所有行返回文件名或操作文件名,具体取决于代码列中是否有值,并且它与文件名中的代码匹配。

所以查询应该返回

Cats and Dogs
xxxx - Cats and Dogs
Baking Cakes
xxxx - Plants
E345 - Tractors

从上面的数据集中。

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

Select Replace(FileName, Code, "xxxx") from table where filename like %Code%

2 个答案:

答案 0 :(得分:2)

您可以尝试以下查询:

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

enter image description here

Demo

这里你不一定需要WHERE条款,因为替换逻辑已经检查是否匹配。请注意,我搜索code -,即您期望它的上下文中的代码。至少部分缓解了可能存在错误替代的可能性。

答案 1 :(得分:0)

试试这个

CREATE TABLE #tmp (Code varchar(25), FileName varchar (25))

INSERT INTO #tmp VALUES
(NULL, 'Cats and Dogs '),
('C123', 'C123 - Cats and Dogs'),
(NULL, 'Baking Cakes'),
('Z345', 'Z345 - Plants'),
('F967', 'E345 - Tractors')

SELECT  
CASE 
      WHEN CHARINDEX(Code, FileName,1)>0 THEN Replace(FileName, Code, 'xxxx') 
      ELSE FileName 
END As Result
FROM #tmp

enter image description here